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

AWS Cloud

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.

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

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.

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).

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

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

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
  1. Open a file at line 20.
nano +20 /etc/hosts

The cursor starts on line 20.

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

Without sudo, Ctrl+O fails with Permission denied.

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

-l prints numbers on the left.

3. Vim modes and survival kit

Vim separates editing commands from typing text. The same key can do different things depending on the mode. Start with a disposable file. Open it in Normal mode, press i to enter Insert mode, and add one line. Press Esc to return to Normal mode, then type :w and Enter to write the file. Exit using :q and open the file again to confirm the saved line.

Try the difference on a second disposable edit. Add a line, leave Insert mode and exit with :q!. When you reopen the file, that new unsaved line is absent. Use this experiment to understand which commands change the buffer and which write changes to disk. When a command looks as though it typed into your file, first check the current mode.

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

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
  1. Open a file.
vim notes.txt

Output:

~
~
"notes.txt" [New]

Normal mode. ~ means empty lines.

  1. Type text.
i  Hello Pune  Esc

Output:

Hello Pune

i entered Insert mode; Esc left it.

  1. Save and quit.
:wq

Output:

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

1 line, 11 bytes saved.

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

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

A safe practice copy opens.

4. Moving fast in Normal mode

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

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.

  1. Jump to the end of the file.
G

Output:

(cursor on the last line)

Great for reading the latest log lines.

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

Output:

(cursor on line 120)

Or open directly: vim +120 app.py.

  1. Move 3 words right.
3w

Count + motion.

  1. Show line numbers.
:set number

Output:

  1 server {
  2   listen 80;

Turn off with :set nonumber.

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

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

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
  1. Delete 3 lines.
3dd

Output:

3 fewer lines

They go into the register, so p can paste them.

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

Delete the line, paste after the next one.

  1. Change a word.
ciw  production  Esc

Output:

env = production

Replaced the word under the cursor.

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

Output:

host = "10.0.1.20"

Works anywhere on the line inside the quotes.

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

n goes to the next search hit, . repeats.

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

Output:

1 change; before #4

Undo is unlimited in a session.

6. Search and replace

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

/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.

  1. Find errors in a log.
/ERROR

Output:

search hit BOTTOM, continuing at TOP

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

% = 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)?

y = yes, n = skip, a = all, q = quit.

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

Output:

11 substitutions on 11 lines

Comments out lines 5–15 (^ = line start).

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

Output:

8 fewer lines

:g runs a command on every matching line.

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

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

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.

  1. Indent a YAML block.
V 4j >

Output:

5 lines >ed 1 time

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 ...

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",

Recorded into register a.

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

Output:

"banana",
"cherry", ...

Same edit, 50 times, in a second.

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

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

Shell output inside your file.

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

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

8. Your .vimrc: make vim yours

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

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

  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

Every new vim session now has these.

  1. Check a setting.
:set tabstop?

Output:

  tabstop=2

? shows the current value.

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

crontab -e and git commit now open vim.

9. Real examples from many industries

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

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

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

Everyone hits these errors. Knowing the cause saves hours.

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

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

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

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

  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

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.

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

  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

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

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

  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.

Practise changes with a copy of a text file

Use vimtutor or a throwaway text file. Enter Insert mode with i, press Escape to return to Normal mode, and use :w to save. To inspect a whole-file replacement without saving, use a copy and choose which changes to keep.

Interview check Why can typing ordinary letters have unexpected effects?

Normal mode interprets keys as commands, while Insert mode enters text. Check the mode and use u to undo a change before saving.

Reference documentation

Practise this chapter

Interview questions and answers

How would you help someone who typed a Vim command and saw it appear as text?

I would have them check the mode indicator. They were likely in Insert mode, where keys add text. Pressing Esc returns to Normal mode; from there they can undo the unintended edit and use the intended command. I would verify the saved file separately from the buffer.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which key moves from Insert mode back to Normal mode in the usual Vim setup?

Answer and explanation

A. Esc

Esc leaves Insert mode, so subsequent editing controls are interpreted as commands.

2. What does :w do after you edit the buffer?

Answer and explanation

B. Writes the buffer to the file

Changes are in memory until written to disk.

3. How can you discard an unsaved practice change on exit?

Answer and explanation

B. Use :q! deliberately

The exclamation form quits without saving the changed buffer.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

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

Jump to the error line.

Open app.py in vim with the cursor on line 120.

  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

Quick edits with context.

Open site.ini in nano with line numbers shown.

  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

System files need root.

Open /etc/motd in nano so you can save changes.

  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

Best free 30-minute lesson.

Start the built-in vim tutorial in French (language code fr).

  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

The most used vim command.

In vim Normal mode, type the command-line command that saves and quits.

  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

You cannot type text in Normal mode.

Which single key enters Insert mode before the cursor?

  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

Fast line removal.

Which Normal-mode keys delete the whole current line?

  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

Copy is called yank.

Which Normal-mode keys copy (yank) the current line?

  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

Every mistake is reversible.

Which single Normal-mode key undoes the last change?

  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

Match line numbers in error messages.

Type the vim command that shows line numbers.

  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

Jump from an error message.

Type the vim command-line command that jumps to line 50.

  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

nano writes out files.

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

  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

A typo can lock out all admins.

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

  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

Change a host in 40 places.

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

  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

Repeat a recorded edit.

You recorded a macro into register a. Type the keys that play it once.

  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

Clean up config files.

Type the vim command that deletes all empty lines in the file.

  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.