Ravindra BagaleCourses & study guides मराठी Track your progress

Vim Tutorial for Beginners to Advanced (plus nano): Modes, Commands, Search and Replace

On many servers there is no VS Code and no mouse. There is always vi or vim. Vim feels strange for one hour and then becomes the fastest editor you know. We start with nano for a quick win, then go from vim's three modes to macros, search-replace and splits.

What you'll learn in this chapter

  • Edit and save with nano in one minute
  • Vim modes: Normal, Insert, Visual, Command-line
  • Move fast: words, lines, file, search
  • Edit: delete, copy, paste, undo, redo, change
  • Search and replace with :s and :%s
  • Advanced: visual block, macros, registers, splits, .vimrc

1. An everyday example: a typewriter with a remote

Why do we need this?

Imagine a typewriter with two buttons. One button puts it in 'typing' mode, so keys print letters. The other puts it in 'remote' mode, so keys move the paper, cut lines and copy pages. Once you know which mode you are in, you never type garbage.

What is it?

Typing mode = Insert mode (press i). Remote mode = Normal mode (press Esc). The control panel where you type :wq = Command-line mode. Selecting with a highlighter = Visual mode (v).

How to do it (step by step)

Vim modesOpen: vim file.txtNormal mode (move, delete)i: Insert mode (type)Esc: back to Normal:wq Enter: save and quit
Esc always brings you back to Normal mode.

2. nano: the quick and friendly editor

Why do we need this?

Sometimes you need to change one line now and do not want to learn modes.

What is it?

nano shows its shortcuts at the bottom. ^ means Ctrl. Type directly. Ctrl+O saves (Write Out). Ctrl+X exits. Ctrl+W searches. Ctrl+K cuts a line, Ctrl+U pastes. Alt+U undoes. Ctrl+_ goes to a line number.

KeysDoes
Ctrl+O, EnterSave
Ctrl+XExit
Ctrl+WSearch
Ctrl+\Search and replace
Ctrl+K / Ctrl+UCut line / paste
Alt+U / Alt+EUndo / redo
Ctrl+_Go to line

How to do it (step by step)

  1. Open a file at line 20.
nano +20 /etc/hosts

What it means: The cursor starts on line 20.

  1. Edit a root-owned file.
sudo nano /etc/ssh/sshd_config

What it means: Without sudo, Ctrl+O fails with Permission denied.

  1. Show line numbers.
nano -l app.conf

What it means: -l prints numbers on the left.

3. Vim modes and survival kit

Why do we need this?

People get 'stuck in vim' because they do not know the modes. Learn these five things and you will never be stuck.

What is it?

Vim opens in Normal mode, where keys are commands. i enters Insert mode to type. Esc returns to Normal. : opens Command-line mode for :w (save), :q (quit), :wq or :x (save and quit), :q! (quit without saving). vimtutor is a 30-minute built-in lesson.

CommandDoes
:wSave
:qQuit (if no changes)
:wq or :x or ZZSave and quit
:q!Quit and throw away changes
:w newnameSave as
:e fileOpen another file

How to do it (step by step)

  1. Open a file.
vim notes.txt

Output:

~
~
"notes.txt" [New]

What it means: Normal mode. ~ means empty lines.

  1. Type text.
i  Hello Pune  Esc

Output:

Hello Pune

What it means: i entered Insert mode; Esc left it.

  1. Save and quit.
:wq

Output:

"notes.txt" [New] 1L, 11B written

What it means: 1 line, 11 bytes saved.

  1. Quit without saving after a mistake.
:q!

What it means: All changes since the last save are gone.

  1. Learn more with the tutor.
vimtutor

Output:

= W e l c o m e   t o   t h e   V I M   T u t o r

What it means: A safe practice copy opens.

4. Moving fast in Normal mode

Why do we need this?

Arrow keys are slow. Vim motions let you jump by words, lines and patterns, and they combine with every edit command.

What is it?

h j k l = left down up right. w = next word, b = back a word, e = end of word. 0 = start of line, ^ = first non-space, $ = end of line. gg = first line, G = last line, 42G or :42 = line 42. Ctrl+d / Ctrl+u = half page down/up. % = matching bracket. A number before a motion repeats it: 5j = 5 lines down.

How to do it (step by step)

  1. Jump to the end of the file.
G

Output:

(cursor on the last line)

What it means: Great for reading the latest log lines.

  1. Jump to line 120 (from an error message).
:120

Output:

(cursor on line 120)

What it means: Or open directly: vim +120 app.py.

  1. Move 3 words right.
3w

What it means: Count + motion.

  1. Show line numbers.
:set number

Output:

  1 server {
  2   listen 80;

What it means: Turn off with :set nonumber.

5. Editing: delete, copy, paste, undo, change

Why do we need this?

Most editing is deleting, copying and changing small pieces. Vim does each in two or three keys.

What is it?

Operator + motion. d = delete, y = yank (copy), c = change (delete then Insert). dd = delete line, yy = copy line, p = paste after, P = paste before. dw = delete word, d$ or D = delete to end of line, ciw = change inner word. x = delete one character. u = undo, Ctrl+r = redo, . = repeat the last change. o / O = new line below/above. A = append at end of line.

KeysDoes
dd / 3ddDelete 1 / 3 lines
yy / pCopy line / paste
dw / cwDelete / change word
ciwChange the whole word under cursor
ci"Change text inside quotes
xDelete a character
u / Ctrl+rUndo / redo
.Repeat last change
>> / <<Indent / unindent line

How to do it (step by step)

  1. Delete 3 lines.
3dd

Output:

3 fewer lines

What it means: They go into the register, so p can paste them.

  1. Move a line down (cut and paste).
ddp

What it means: Delete the line, paste after the next one.

  1. Change a word.
ciw  production  Esc

Output:

env = production

What it means: Replaced the word under the cursor.

  1. Change a value in quotes.
ci"  10.0.1.20  Esc

Output:

host = "10.0.1.20"

What it means: Works anywhere on the line inside the quotes.

  1. Repeat the same change on the next match.
n.

What it means: n goes to the next search hit, . repeats.

  1. Undo twice, redo once.
u u Ctrl+r

Output:

1 change; before #4

What it means: Undo is unlimited in a session.

6. Search and replace

Why do we need this?

Changing a host name in 40 places by hand is slow and error-prone.

What is it?

/text searches forward, ?text searches back, n = next, N = previous, * = search the word under the cursor. :s/old/new/ replaces the first match on the line. :%s/old/new/g replaces all in the file. Add c to confirm each: :%s/old/new/gc. :10,20s/// limits to lines 10–20. :noh clears highlight.

How to do it (step by step)

  1. Find errors in a log.
/ERROR

Output:

search hit BOTTOM, continuing at TOP

What it means: Press n for the next one.

  1. Replace all in the file.
:%s/db-old.internal/db-new.internal/g

Output:

12 substitutions on 12 lines

What it means: % = whole file, g = every match on each line.

  1. Replace with confirm.
:%s/8080/9090/gc

Output:

replace with 9090 (y/n/a/q/l/^E/^Y)?

What it means: y = yes, n = skip, a = all, q = quit.

  1. Only in lines 5 to 15.
:5,15s/^/# /

Output:

11 substitutions on 11 lines

What it means: Comments out lines 5–15 (^ = line start).

  1. Delete all blank lines.
:g/^$/d

Output:

8 fewer lines

What it means: :g runs a command on every matching line.

7. Advanced: visual mode, macros, registers, splits

Why do we need this?

For big edits (YAML blocks, CSV columns, the same change on 200 lines) you need power tools.

What is it?

v = select characters, V = select lines, Ctrl+v = select a block (columns). After selecting: d, y, >, < or : work on it. Macros: qa starts recording into register a, q stops, @a plays, 10@a plays 10 times. Registers: "ayy copies into a, "ap pastes from a, "+y copies to system clipboard. Splits: :split and :vsplit, Ctrl+w w to move. :!cmd runs a shell command. :r !cmd inserts its output.

How to do it (step by step)

  1. Indent a YAML block.
V 4j >

Output:

5 lines >ed 1 time

What it means: Selected 5 lines and shifted them right.

  1. Add # to the start of 10 lines (block insert).
Ctrl+v 9j I # Esc

Output:

# line1
# line2 ...

What it means: I in block mode types on every selected line.

  1. Record a macro that quotes a word and moves down.
qa I" Esc A", Esc j q

Output:

"apple",

What it means: Recorded into register a.

  1. Play it on 50 more lines.
50@a

Output:

"banana",
"cherry", ...

What it means: Same edit, 50 times, in a second.

  1. Open two files side by side.
:vsplit nginx.conf

What it means: Ctrl+w w jumps between windows.

  1. Insert today's date from the shell.
:r !date

Output:

Sun Oct 25 11:02:10 IST 2026

What it means: Shell output inside your file.

  1. Save a root file you opened without sudo.
:w !sudo tee % > /dev/null

What it means: % is the current file name. Reload with :e! after.

8. Your .vimrc: make vim yours

Why do we need this?

Typing :set number every time is boring. Settings in ~/.vimrc load on every start.

What is it?

~/.vimrc is a text file of settings. Good starters: number, relativenumber, tabs as spaces for YAML, search options and syntax on.

How to do it (step by step)

  1. Write a starter .vimrc.
cat > ~/.vimrc <<'V'
syntax on
set number relativenumber
set expandtab tabstop=2 shiftwidth=2
set ignorecase smartcase incsearch hlsearch
set paste?
V

What it means: Every new vim session now has these.

  1. Check a setting.
:set tabstop?

Output:

  tabstop=2

What it means: ? shows the current value.

  1. Set vim as the default editor (git, crontab, visudo).
echo 'export EDITOR=vim VISUAL=vim' >> ~/.bashrc && source ~/.bashrc

What it means: crontab -e and git commit now open vim.

9. Real examples from many industries

Why do we need this?

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

What is it?

Each row is a made-up team. It shows who uses this and how.

How to do it (step by step)

Team and cityHow they use itCommand
Vikram, SRE, NoidaFixes nginx config on a live server with vimsudo vim /etc/nginx/nginx.conf
Chloe, Kubernetes, SydneyEdits YAML with expandtab and visual indentkubectl edit deploy web
Javier, data, BogotáTurns a CSV column into SQL with a macroqa ... q 200@a
Sneha, support, KochiUses nano for quick hosts file editssudo nano /etc/hosts
Yusuf, security, IstanbulEdits sudoers safelysudo visudo
Aarav, student, DelhiWrites git commit messages in vimgit commit
Nora, embedded, MunichUses vi on BusyBox devices with no vimvi /etc/config/network

10. Common errors and how to fix them

Why do we need this?

Everyone hits these errors. Knowing the cause saves hours.

What is it?

Read the exact message first. Then match it to a row below.

How to do it (step by step)

Error you seeWhy it happensHow to fix
E37: No write since last change (add ! to override)You tried :q with unsaved changesUse :wq to save, or :q! to discard.
:wq
E45: 'readonly' option is set (add ! to override)File opened read-only (view, or -R)Use :w! if you own it, or reopen properly.
:w!
E212: Can't open file for writingNo permission (root file) or folder missingSave with sudo tee, or reopen with sudo.
:w !sudo tee % > /dev/null
E325: ATTENTION Found a swap file by the name ".app.conf.swp"Vim crashed earlier or the file is open elsewherePress R to recover, or D to delete the swap if it is old.
ls -la .*.swp
Typed text appears as commands (letters vanish, lines deleted)You were in Normal mode, not Insert modePress Esc, then u to undo, then i to insert.
u
E486: Pattern not found: ErrorSearch is case sensitiveUse /\cerror or :set ignorecase.
:set ignorecase
Pasted code gets extra indent (staircase)Auto-indent runs on pasteUse :set paste before pasting, then :set nopaste.
:set paste
Stuck in 'Recording @q'You pressed q followed by a letterPress q again to stop.
q
Error 'mapping' or tab errors in YAML after editingTabs were inserted instead of spacesSet expandtab and run :retab.
:set expandtab | retab
nano: Error writing /etc/hosts: Permission deniednano opened without sudoExit and reopen with sudo nano.
sudo nano /etc/hosts

11. Troubleshooting step by step

Why do we need this?

When vim behaves oddly, it is almost always the mode, the file permission or a setting.

What is it?

Go top to bottom. Stop at the first step that shows the problem.

How to do it (step by step)

  1. Press Esc twice. Now you are in Normal mode.
  1. Undo what happened.
u
  1. Check the mode line at the bottom (INSERT, VISUAL, recording).
  1. Check whether you can write the file.
:!ls -l %
  1. Check settings that change typing.
:set paste? expandtab? autoindent?
  1. Start clean without your vimrc.
vim -u NONE file

12. Lab 1: Fix a broken config with vim only

Why do we need this?

Grace is on call for a bakery chain in Cape Town. The app config points to an old database and has a wrong port. Fix it in vim.

What is it?

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

How to do it (step by step)

  1. Create the file.
printf 'db_host = "db-old.internal"\ndb_port = 5433\nreplica = "db-old.internal"\ndebug = true\n' > app.conf
  1. Open it with numbers.
vim +'set number' app.conf

Output:

  1 db_host = "db-old.internal"
  2 db_port = 5433
  3 replica = "db-old.internal"
  4 debug = true
  1. Replace the host everywhere.
:%s/db-old/db-new/g

Output:

2 substitutions on 2 lines
  1. Go to line 2 and change the port.
:2 then $ ciw 5432 Esc

Output:

db_port = 5432
  1. Delete the debug line.
G dd

Output:

3 lines
  1. Save and quit, then check.
:wq then cat app.conf

Output:

db_host = "db-new.internal"
db_port = 5432
replica = "db-new.internal"

13. Lab 2: Turn a list into JSON with a macro

Why do we need this?

Convert 100 city names into a JSON array in under a minute.

What is it?

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

How to do it (step by step)

  1. Make the list.
printf '%s\n' Pune Mumbai Delhi Paris Lagos Lima > cities.txt && vim cities.txt
  1. Record: quote the line, add a comma, go down.
qq I" Esc A", Esc j q

Output:

"Pune",
  1. Play on the rest.
100@q

Output:

"Mumbai",
...
"Lima",
  1. Remove the last comma.
G $ x
  1. Add brackets.
gg O [ Esc G o ] Esc :wq

Output:

[
"Pune",
...
"Lima"
]
  1. Validate.
python3 -m json.tool cities.txt | head -3

Output:

[
    "Pune",
    "Mumbai",

Ravindra Bagale's Tip

Lost in vim? Press Esc twice, then type :q! and Enter. You are out with no damage. Then spend 30 minutes with vimtutor, it is the best free vim course.

14. Frequently asked questions

Q. vi vs vim?

vi is the old editor in every Unix. vim is 'vi improved' with undo levels, syntax colours and plugins. On many systems vi starts vim.

Q. Should I learn nano or vim?

Both. nano for a quick edit, vim because it is everywhere and much faster for real work.

Q. How do I copy to my laptop clipboard?

In a GUI or with clipboard support use "+y. Over SSH, select with the mouse in the terminal.

Q. What is Neovim?

A modern fork of vim with Lua config and built-in LSP. Same keys.

Q. How do I edit sudoers safely?

Always with visudo. It checks syntax before saving, so you cannot lock yourself out.

15. Interview questions and answers

Beginner level

Q. How do you save and quit vim?

:wq or :x or ZZ.

Q. How do you quit without saving?

:q!

Q. How do you enter Insert mode?

i (or a, o, A, I).

Q. How do you save in nano?

Ctrl+O then Enter.

Mid level level

Q. How do you replace all occurrences in a file?

:%s/old/new/g, add c to confirm.

Q. What does . do?

Repeats the last change.

Q. Difference between v, V and Ctrl+v?

Character, line and block selection.

Q. How do you go to line 50?

:50 or 50G.

Senior level

Q. You opened /etc/nginx/nginx.conf without sudo and made 30 edits. How do you save?

:w !sudo tee % > /dev/null, then :e! to reload. Or save to /tmp and sudo cp.

Q. Explain a macro and when you would use it.

A recorded sequence of keys in a register (qa ... q, @a). Use it for repetitive structured edits like reformatting lines.

Q. What is a swap file and how do you handle E325?

Vim's crash-recovery file. Recover (R) if vim crashed, delete if old, or open read-only if someone else is editing.

Q. How do you keep YAML safe in vim?

set expandtab tabstop=2 shiftwidth=2, :set list to see tabs, and :retab to convert.

Try at home

  1. Run vimtutor for 30 minutes.
  2. Create ~/.vimrc with the starter settings.
  3. Use :%s to change a word in a test file.

Practice Tasks

About this scenario

Ahmednagar Sugar Co-op is a sugar co-operative business in Ahilyanagar. Balasaheb Pawar looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Open a file at a line

Why: Jump to the error line.

What to do: Open app.py in vim with the cursor on line 120.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy nano with line numbers

Why: Quick edits with context.

What to do: Open site.ini in nano with line numbers shown.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Edit a root file in nano

Why: System files need root.

What to do: Open /etc/motd in nano so you can save changes.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Start the vim tutor

Why: Best free 30-minute lesson.

What to do: Start the built-in vim tutorial in French (language code fr).

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Save and quit

Why: The most used vim command.

What to do: In vim Normal mode, type the command-line command that saves and quits.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Enter Insert mode

Why: You cannot type text in Normal mode.

What to do: Which single key enters Insert mode before the cursor?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Delete a line

Why: Fast line removal.

What to do: Which Normal-mode keys delete the whole current line?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Copy a line

Why: Copy is called yank.

What to do: Which Normal-mode keys copy (yank) the current line?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Undo

Why: Every mistake is reversible.

What to do: Which single Normal-mode key undoes the last change?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Show line numbers

Why: Match line numbers in error messages.

What to do: Type the vim command that shows line numbers.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Go to line 50

Why: Jump from an error message.

What to do: Type the vim command-line command that jumps to line 50.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Save in nano

Why: nano writes out files.

What to do: Which key combination saves the file in nano? Write it like ctrl+x.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Edit sudoers safely

Why: A typo can lock out all admins.

What to do: Open the drop-in file /etc/sudoers.d/40-ops with the safe editor that checks syntax.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Replace in the whole file

Why: Change a host in 40 places.

What to do: Type the vim command that replaces every db-old with db-new in the whole file.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Play a macro

Why: Repeat a recorded edit.

What to do: You recorded a macro into register a. Type the keys that play it once.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Delete blank lines

Why: Clean up config files.

What to do: Type the vim command that deletes all empty lines in the file.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

In short

  1. nano: Ctrl+O save, Ctrl+X exit.
  2. vim: Esc for Normal, i for Insert, :wq to save and quit, :q! to escape.
  3. Operator + motion: dd, yy, p, ciw, u, .
  4. :%s/old/new/g, visual block, macros @a.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Vim modes. Edit config on any server. Normal, Insert, Visual, Command. i to type, Esc to go back. Save and quit.
Revision card: Vim modes · Download PNG · Open card page
Vim editing. Fast edits without a mouse. dd delete, yy copy, p paste. u undo, /word to search. Replace in whole file.
Revision card: Vim editing · Download PNG · Open card page
Vim vs nano. Modal power editor. / Simple editor.
Comparison: Vim vs nano · Download PNG · Open card page
:wq vs :q!. Save and quit. / Quit without saving.
Comparison: :wq vs :q! · Download PNG · Open card page
How to exit Vim?. Press Esc first. :wq saves, :q! drops changes. Shortcut save and quit.
Interview card: How to exit Vim? · Download PNG · Open card page
Vim says swap file exists?. Last edit crashed, or is open. Recover, or delete the swap. Recover the file.
Interview card: Vim says swap file exists? · Download PNG · Open card page
Edited as user, need root?. Do not lose your changes. Write through sudo tee. Next time use sudoedit.
Interview card: Edited as user, need root? · Download PNG · Open card page
Vim or nano on a server?. Vim is on almost every server. nano is easier to start. Learn Vim basics anyway.
Interview card: Vim or nano on a server? · Download PNG · Open card page

More cards: Ravi Sir's Cards.