vi Text Editor

vi Text Editor #

vi is a powerful and widely-used text editor in the Unix/Linux world. Vim, which stands for Vi IMproved, is an extended version of vi with additional features, making it even more powerful. Many Linux distributions come with Vim installed by default, and you can still access it using the vi command.

Opening & Closing Files #

To open a file with Vim, simply type vi followed by the file name:

vi myfile.txt

If the file does not exist, Vim will create a new one with the specified name once you save your changes.

To close Vim, press the Esc key (to ensure you’re in Command mode), then type :q and hit return. If you have unsaved changes, Vim will prevent you from closing. To close without saving, type :q!. To save your changes before closing, type :wq.

Vim modes #

Vim operates in different modes designed for specific tasks:

  • Command mode → This is the default mode when you open Vim. You can navigate, delete, copy, paste, and perform other editing tasks in this mode. Press Esc to return to Command mode from Insert mode.

  • Insert mode → In this mode, you can insert text into the file. Press i to enter Insert mode from Command mdoe.

Vim commands #

CommandsDescription
h j k and lNavigate left, down, up, and right
ggMove to the beginning of the file
GMove to the end of the file
:123Jump to line 123
75%Jump to line located at 75% of the file

Editing #

CommandsDescription
iEnter Insert mode before the current cursor position
aEnter Insert mode after the current cursor position
oInsert a new line below the current line and enter Insert mode
OInsert a new line above the current line and enter Insert mode
ddDelete the current line
yyCopy the current line
pPaste the copied content after the current line
PPaste the copied content before the current line
uUndo the last change

Searching and Replacing #

CommandsDescription
/patternSearch for a pattern in the file (press n to move to the next match and N to move to the previous match)
:%s/old/new/gReplace all occurrences of “old” with “new” in the entire file
:s/old/new/gReplace all occurrences of “old” with “new” in the current line

Saving and Exiting #

CommandsDescription
:wSave
:qQuit (will not close if there are unsaved changes)
:q!Force quit without saving changes
:wqSave changes and quit
:x or ZZSave changes (if any) and quit

This is just a brief introduction to Vim. There are many more features and commands available.