Vi editor tips and tricks

From Thomas-Krenn-Wiki
Jump to: navigation, search

vi (or vim) is the default editor in many Unix- and Linux-based operating systems. This article provides some tips and tricks for vi/vim. A good learning aid is also the vimtutor command.


A file is opened with vi:


In the bottom line, for example, you see:

"" 66L, 204C                                       1,1           Top

You can now navigate with the cursor keys, but you cannot enter any text. To enter a text, switch to insert mode by pressing the key i:


The bottom line now displays this:

-- INSERT --                                                  1,1           Top


After writing some text, press the Esc key to return to normal mode:


By typing :w, the new state of the file can now be saved:


The bottom line now displays:

"" 72L, 223C written                               4,1           Top

If you want to save and exit vi at the same time, type :x:



If you want to quit (without saving), :q is used:


Exit and discard changes

If you edited the file and want to exit and discard your changes, add ! to :q:


Delete line

Lines can be deleted with the command dd (deletes a line). If you want to delete more than one line (e. g. five), type in the number beforehand. For example, the following key sequence is used to delete five lines:


The bottom line now displays:

5 fewer lines                                                 1,0-1         Top

Copy lines

If lines have been deleted with dd, they are still cached. By pressing p at another position, the rows are inserted again:


The bottom line displays:

5 more lines                                                  8,1           Top

If you want to copy lines, but do not want to delete them, use the yy keys instead of dd - in this case for five lines again:


The bottom line displays:

5 lines yanked                                                12,0-1        Top

The lines can be pasted again with p.

Set the offset of a tab

When using tabs, it often happens that you want to set the number of blanks for the tab offset. Usually, eight blanks are defined for this purpose. For example, to use 4 spaces instead, type:

:set ts=4

Search and replace

Vi also provides a search&replace function

The following string replaces OLD with NEW:


Tabs in vi

Using the command


you can open a second tab in vi.

The following commands are useful when working with tabs:

list all tabs
switch to the next tab
switch to the previous tab


The vimdiff command can be used to compare two, three or four files with vi side by side.

You can switch between the files with [Strg] + [W] + [W].


vimdiff test1 test2


Author: Thomas Niedermeier

Related articles

Linux I/O Performance Tests using dd
Linux Performance Measurements using vmstat
Using Md5sum und sha1sum for Checking Downloaded Files