ag@linux:~$

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

  1. Go to the command line and type vi, a space, then the file name:

    Terminal window
    vi filename

    If the file does not exist yet, vi opens an empty buffer and creates the file when you save.

  2. To insert text, press I.

    vi starts in normal (command) mode, where keys are commands rather than text. I switches to insert mode with the cursor at the start of the current line. Lowercase i, which inserts before the cursor, is the one most people use.

  3. Type the text you want.

  4. Press Esc to go back to normal mode.

  5. To save, type :w and press Enter.

    Correction: the original said :R to save. That is wrong. :w (write) saves the file. :r does something different: it reads another file into the current one.

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

Terminal window
vi notes.txt
  1. Press i and type hello.

  2. Press Esc.

  3. Type :wq and press Enter.

  4. 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 u to undo, then i before typing.
  • Editing system files such as those in /etc without permission. vi will open them but refuse to save. Run as root or with sudo (for example sudo vi /etc/hosts).
  • On most modern distributions vi starts Vim, an improved version of vi. All the commands above work in both.