Using the vi and vim Text Editors

vi is a text editor found on almost every Linux and Unix system, and vim is its improved version. It is very fast once you know it, but it works differently from other editors, so it helps to learn a few keys first.

Opening and quitting

vi file.txt
Opens file.txt, or creates it when you save if it doesn't exist.
:wq
Saves and quits. Type it in normal mode and press Enter. :x does the same.
:q!
Quits without saving your changes.

Stuck in vi? Press Esc a couple of times, then type :q! and press Enter to quit without saving.

Modes

vi has modes. In normal mode the keys are commands. In insert mode the keys type text. Press Esc to go back to normal mode at any time.

KeyWhat it does
iInsert text before the cursor
aInsert text after the cursor
oStart a new line below and insert
EscGo back to normal mode
:Type a command, such as :w

Moving around

KeyWhat it does
h j k lLeft, down, up, right (the arrow keys work too)
w / bNext / previous word
0 / $Start / end of the line
gg / GTop / bottom of the file
:42Go to line 42
Ctrl + f / Ctrl + bPage down / page up

Editing

KeyWhat it does
xDelete the character under the cursor
ddDelete (cut) the line
5ddDelete 5 lines
yyCopy (yank) the line
pPaste below the cursor
uUndo
Ctrl + rRedo
.Repeat the last change

Saving and quitting

KeyWhat it does
:wSave
:wq or :xSave and quit
:qQuit (only if nothing has changed)
:q!Quit and throw away changes

Search and replace

KeyWhat it does
/wordSearch forward for word
n / NNext / previous match
:%s/old/new/gReplace every old with new in the file
:%s/old/new/gcReplace, asking to confirm each one

Handy settings

KeyWhat it does
:set numberShow line numbers
:syntax onColour code the text
:set pastePaste text without extra indenting