history 10 of 36
Basic VI Editor Commands: Open, Insert, Save and Quit
The first vi editor commands a beginner needs: open a file, switch to insert mode, type text, then save or quit, with the original save command corrected.
Written
From my Linux study notes, 2013. Some commands and versions here are old, so please reuse them carefully. Anything marked "added later", and the notes at the end, explain what has changed since.
The original steps
-
Go to the command line and type
vi, a space, then the file name:Terminal window vi filenameIf the file does not exist yet, vi opens an empty buffer and creates the file when you save.
-
To insert text, press
I.vi starts in normal (command) mode, where keys are commands rather than text.
Iswitches to insert mode with the cursor at the start of the current line. Lowercasei, which inserts before the cursor, is the one most people use. -
Type the text you want.
-
Press Esc to go back to normal mode.
-
To save, type
:wand press Enter.Correction: the original said
:Rto save. That is wrong.:w(write) saves the file.:rdoes something different: it reads another file into the current one. -
To quit without saving, type
:q!and press Enter.
Notes for today
Common commands
All of these are typed in normal mode (press Esc first). Commands starting with : need Enter afterwards.
| Command | What it does |
|---|---|
i |
Insert before the cursor |
I |
Insert at the start of the line |
a |
Append after the cursor |
A |
Append at the end of the line |
o |
Open a new line below and insert |
Esc |
Return to normal mode |
:w |
Save |
:wq |
Save and quit |
:x |
Save (only if changed) and quit |
:q |
Quit (refuses if there are unsaved changes) |
:q! |
Quit and throw away changes |
u |
Undo the last change |
x |
Delete the character under the cursor |
dd |
Delete the current line |
h j k l |
Move left, down, up, right (arrow keys usually work too) |
/text |
Search forward for “text”; n goes to the next match |
A worked example
vi notes.txt-
Press
iand typehello. -
Press Esc.
-
Type
:wqand press Enter. -
Check the file:
Terminal window cat notes.txt
Common mistakes
- Typing text while in normal mode. Letters run as commands, which can change the file in unexpected ways. Press Esc, then
uto undo, thenibefore typing. - Editing system files such as those in
/etcwithout permission. vi will open them but refuse to save. Run as root or withsudo(for examplesudo vi /etc/hosts). - On most modern distributions
vistarts Vim, an improved version of vi. All the commands above work in both.