Using the Vim Editor

Managing Linux often means working with files. Most of the things that are configured on Linux are configured through files. To get things done, you often need to change the contents of a configuration file with a text editor.

Over the years, many text editors have been created for Linux. One editor really matters, though, and that is vi. Even if some other text editors are easier to use, vi is the only text editor that is always available. That is why as a Linux administrator you need to know how to work with vi. Only one alternative is permitted, and that is vim. Vim is “vi improved;” it is a complete rewrite of vi with a lot of enhancements that make working with vi easier, such as syntax highlighting for many configuration files which makes it easy to recognize typing errors that you have made. All that you learn in this section about vim works on vi as well.

An important concept when working with vim is that it uses different modes. Two of them are particularly important: command mode and input mode. These modes often cause confusion because in command mode you can just enter a command and you cannot change the contents of a text file. To change the contents of a text file, you need to get to input mode.

The challenge when working with vim is the vast number of commands that are available. Some people have even produced vi cheat sheets, listing all available com- mands. Do not use them. Instead, focus on the minimal number of commands that are really important. Table below summarizes the most essential vim commands.

Vim Command Explanation
Esc Switches from input mode to command mode. Use this before typing any command.
i, a Switches from command mode to input mode at (i) or after (a) the current cursor position.
o Opens a new line below the current cursor position and goes to input mode.
:wq Writes the current file and quits.
:q! Quits the file without applying any changes. The ! forces the command to do its work. Only add the ! if you really know what you are doing.
:w filename Writes the current file with a new filename
dd Deletes the current line.
yy Copies the current line.
p Pastes the current selection.
v Enters visual mode, which allows you to select a block of text using the arrow keys. Usedto cut, oryto copy the selection.
u Undoes the last command. Repeat as often as necessary.
Ctrl+R Redoes the last undo.
gg Goes to the first line in the document.
G Goes to the last line in the document.
/text Searches for text from the current cursor position forward.
?text Searches for text from the current cursor position backward.
^ Goes to the first position in the current line.
$ Goes to the last position in the current line.
!ls Adds the output of ls (or any other command) in the current file.
:%s/old/new/g Replaces all occurrences ofoldwithnew.