vi and vim: the essential commands

Updated November 2026

vi is the editor you will find on every Unix system, from tiny routers to mainframes. On Linux, vi usually starts vim ("vi improved"). It looks strange at first because it has modes, but a dozen commands are enough for everyday editing.

vi [file ...] vim +NUMBER file # open at a line

Modes

When in doubt, press Esc twice to get back to normal mode.

Save and quit

TypeDoes
:wSave
:wq or :x or ZZSave and quit
:qQuit (only if nothing changed)
:q!Quit and throw away changes
:w newnameSave as another file
:w !sudo tee %Save a file you opened without sudo (vim)

Insert text

KeyStarts inserting
i / aBefore / after the cursor
I / AAt the start / end of the line
o / OOn a new line below / above

Move around (normal mode)

KeyMoves
h j k l (or arrows)Left, down, up, right
w / bNext / previous word
0 / $Start / end of line
gg (vim) or 1G / GFirst / last line
:42 or 42GLine 42
Ctrl+f / Ctrl+bPage down / up

Edit (normal mode)

KeyDoes
xDelete the character under the cursor
dd / 5ddDelete (cut) a line / five lines
dw, d$Delete a word, to the end of the line
yy / 5yyCopy (yank) a line / five lines
p / PPaste after / before
cwChange a word (delete it and insert)
rxReplace one character with x
u / Ctrl+rUndo / redo (vim; in classic vi, u undoes the last change and pressing it again redoes it)
.Repeat the last change
v, VSelect characters / lines (vim), then d or y

Search and replace

/error          search forward for "error" (n = next, N = previous)
?error          search backward
:%s/old/new/g   replace every "old" with "new" in the file
:%s/old/new/gc  the same, asking for each one
:10,20s/^/# /   comment out lines 10 to 20
:set ic         ignore case in searches

The replace syntax is the same as in sed.

Make vim friendlier

Put these lines in ~/.vimrc:

syntax on
set number          " line numbers
set ignorecase smartcase
set incsearch hlsearch
set expandtab shiftwidth=4 tabstop=4
set mouse=a

Run vimtutor for a 30-minute interactive lesson. If you prefer a simpler editor, nano is installed on most Linux systems. To make another editor the default for tools such as crontab -e and visudo, set export EDITOR=nano or run sudo update-alternatives --config editor on Debian and Ubuntu.