Vi Editor Commands

Linux

Here are a few useful commands for those who are new to vi.

esc :q! Just quit – don’t save
esc :e! Revert to saved
esc :wq Save and exit
esc shift zz Save and exit
esc i Enter insert mode (edit mode)
esc a Enter append mode (edit mode)
esc Exit edit mode
esc r Replace a single character
esc x Delete a single character
esc  u Undo last Change
esc  U Undo all changes to line
esc dd Delete a single line
esc yy Copy a single line
esc p Paste a single line
. Repeat the last command
esc / String search
esc $ Jump to end of line
esc ^ Jump to begining of line
shift g (or) :$ Jump to the end of the file
:1  or gg Jump to the begining of the file
:.= Display the current line number
nG  (or) :n Move to nth line of the file
:set nu To turn ON numbering to each line
:set nonu To turn OFF numbering to each line

FIND & REPLACE :

Syntax:          :%s/WORD-To-Find-HERE/Replace-Word-Here/g

Examples

To find each occurrence of ‘UNIX’, and replace it with ‘Linux’, enter (press ESC, type : and following command):
                                 :%s/UNIX/Linux/g

Task: Find and Replace with Confirmation

Find a word called ‘UNIX’ and replace with ‘Linux’, but ask for confirmation first, enter:
:%s/UNIX/Linux/gc

Task: Find and Replace Whole Word Only

Find whole words exactly matching ‘UNIX’ to ‘Linux’; and ask for confirmation too:
:%s/\<UNIX\>/Linux/gc

Task: Case Insensitive Find and Replace

Find ‘UNIX’ (match UNIX, unix, UnIx, Unix and so on) and replace with ‘Linux’:
:%s/unix/Linux/gi

Same command with confirmation:
:%s/unix/Linux/gic

Task: Case sensitive Find and Replace

Find each ‘UNIX’ and replace with ‘bar’:
:%s/UNIX/bar/gI

Same command with confirmation:

:%s/UNIX/bar/gIc

How Do I Replace In the Current Line Only?

Find ‘UNIX’ and replace with ‘Linux’ in the current line only (note % is removed from substitute command)
       :s/UNIX/Linux/g

NOTE: You need to prefix % the substitute command to make changes on all lines:

     :%s/UNIX/Linux/g

 How Do I Replace All Lines Between line 100 and line 250?

     :{START-n},{END-n}s/word1/word2/g

EX : Find ‘UNIX’ and replace with ‘Linux’ all lines between line 100 and line 250, enter
:100,200s/UNIX/Linux/g

OR
           :100,200s/UNIX/Linux/gc

Task :  Count the word ABC  in entire vi file     :%s/ABC/ABC/g