Vi editor Tutorial and examples

**Search and Replace **

Append a string to start of  every other line:

g#^# if line('.')%2|s#^#http://test #


:g/^/ if line('.')%2 | s/^/word/


:g/^/ if line('.')%2|s/^/zz /

Search and Replace a string :


[ Options : g = Replace each occurence, c = ask for confirmation , i = case insensitive , I = case sensitive for confirmation]

Using Range for search and replace:


Options :[s = Current Line], [%s = all lines], [1,10s = from line 1 to line 10], [ ‘a,’bs = between mark a and mark b –inclusive]

[.,+2s = current line and next two lines ] [ g/^test/s = For each line starting with test ]

Special Characters for Search :

[  .,*,,[,],^, $  = meta characters]             [+,?,|,{,},(,)  = need to be escaped to use their function ]

[/  = / , \t = tab , \s = whitespace, \n = new line , \r = CR  = CTRL M = ^M, {#} = reptition eg. /test.{2} will match test following two chars ]

Special Characters for Replace :

[ \r is newline, \n is null byte (0x00), & = ampersand , & = text which matches search pattern , \1 = insert text of first backreference ]

Note : Other delimeters can be used with subtitute : eg. :s#search/replace#

Save some typing : eg.

:%s/Testing in 2006 was fine/Testing in 2008 was fine/

could be done as :

:%s/Testing \zs2006\ze was fine/2008/

Append a String to each Line in VI

Go to the Exec Mode


Prepend a string to each line :


Replace first  occurence of a string:


Replace last occurence of string :


Delete a word and all text to the end of line in each line :


Delete a word and next 10 characters on each line :


Delete all text following word to the end of line on each line:


Delete the word and all text before word on each line :


Delete all text before a word on each line :


Delete all text  before and after a word :


Delete blank Lines in VI:

:g/^$/ d

Select and Delete a block :

Move your cursor to the point where you want to start selection and press :


now move to the end where you want to delete and then type :


Where a is the marker and .d means delete the selected block.

Other Advanced Commands you can carry out with selected blocks :

Yank from ‘a to current line and put in buffer ‘b’

:'a,.ya b

Yank from 'a to current line and append to buffer 'b'

:'a,.ya B

Search And Replace between mark  a to current line:


(i.e. comment out in Perl)

:'s,.s#^#//# - from 'a to current line, substitute '//' for line begin

** Copy from one file and paste to another File:**

Yank the lines you want from source file :


Open another file you want to paste to :

:e filename

Paste the copied lines:


Save the changes


Return to Original File: