vi and vim: the essential commands
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
- Normal mode (where you start): keys are commands for moving, deleting and copying.
- Insert mode: keys type text. Enter it with i, leave it with Esc.
- Command-line mode: press : in normal mode to type commands such as
:w(write) and:q(quit).
When in doubt, press Esc twice to get back to normal mode.
Save and quit
| Type | Does |
|---|---|
:w | Save |
:wq or :x or ZZ | Save and quit |
:q | Quit (only if nothing changed) |
:q! | Quit and throw away changes |
:w newname | Save as another file |
:w !sudo tee % | Save a file you opened without sudo (vim) |
Insert text
| Key | Starts inserting |
|---|---|
| i / a | Before / after the cursor |
| I / A | At the start / end of the line |
| o / O | On a new line below / above |
Move around (normal mode)
| Key | Moves |
|---|---|
| h j k l (or arrows) | Left, down, up, right |
| w / b | Next / previous word |
| 0 / $ | Start / end of line |
| gg (vim) or 1G / G | First / last line |
:42 or 42G | Line 42 |
| Ctrl+f / Ctrl+b | Page down / up |
Edit (normal mode)
| Key | Does |
|---|---|
| x | Delete the character under the cursor |
| dd / 5dd | Delete (cut) a line / five lines |
| dw, d$ | Delete a word, to the end of the line |
| yy / 5yy | Copy (yank) a line / five lines |
| p / P | Paste after / before |
| cw | Change a word (delete it and insert) |
| rx | Replace one character with x |
| u / Ctrl+r | Undo / redo (vim; in classic vi, u undoes the last change and pressing it again redoes it) |
| . | Repeat the last change |
| v, V | Select 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.