vi Editor commands and use

Sharing is caring!

The default editor that comes with the UNIX operating system is called vi (visual editor). [Alternate editors for UNIX environments include pico and emacs, a product of GNU.]  
vi can be used from any type of terminal because it does not depend on arrow keys and function keys–it uses the standard alphabetic keys for commands. vi has two modes:

  • command mode
  • insert mode

In command mode, the letters of the keyboard perform editing functions (like moving the cursor, deleting text, etc.). To enter command mode, press the escape key.
In insert mode, the letters you type form words and sentences. Unlike many word processors, vi starts up in command mode.

Starting vi

You may use vi to open an already existing file by typing

      vi filename

where “filename” is the name of the existing file. If the file is not in your current directory, you must use the full pathname.
Or you may create a new file by typing

      vi newfilename
      vi -r filename     (Recover a file, being edited before system crashed) 
 
 Note: 
 
The cursor moves to bottom of screen whenever a colon (:) is typed. This type of command is completed by hitting the (or ) key.
Entering Text

In order to begin entering text in this empty file, you must change from command mode to insert mode. To do this, type
i

Moving the Cursor

The cursor is controlled with four keys: h, j, k, l.

 h left one space j down one line k up one line l right one space 

BASIC EDITING

     x         delete character
nx delete n characters
X delete character before cursor
dw delete word
ndw delete n words
dd delete line
ndd delete n lines
D delete characters from cursor to end of line
r replace character under cursor
cw replace a word
ncw replace n words
C change text from cursor to end of line
o insert blank line below cursor
(ready for insertion)
O insert blank line above cursor
(ready for insertion)
J join succeeding line to current cursor line
nJ join n succeeding lines to current cursor line
u undo last change
U restore current line

MOVING AROUND IN A FILE

     w            forward word by word
b backward word by word
$ to end of line
0 (zero) to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
f scroll forward one screen
b scroll backward one screen
d scroll down one-half screen
u scroll up one-half screen
n repeat last search in same direction
N repeat last search in opposite direction

Closing and Saving a File

To save the edits you have made, but leave vi running and your file open:

  1. Press .
  2. Type :w
  3. Press .

 Quit and Discard changes

To quit vi, and discard any changes your have made since last saving:

  1. Press .
  2. Type :q!
  3. Press .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.