Vi editor Tutorial and examples

**Search and Replace **

Append a string to start of  every other line:

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

or

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

or

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

Search and Replace a string :

%s/string/newstring/

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

Using Range for search and replace:

:/string/newstring/g

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

:%s/$/stringtoappend/g

Prepend a string to each line :

:%s/^/string/g

Replace first  occurence of a string:

:%s/string/newstring/

Replace last occurence of string :

:%s/.*\zsstring/newstring/

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

:%s/<string>.*//

Delete a word and next 10 characters on each line :

:%s/<string>.{10}//

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

:%s/<foo>\zs.*//

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

%s/.*<foo>//

Delete all text before a word on each line :

:%s/.*\ze<foo>//

Delete all text  before and after a word :

:%s/.(<foo>)./\1/

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 :

ma

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

:'a,.d

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:

:'a,.s/^/#/

(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 :

5yy

Open another file you want to paste to :

:e filename

Paste the copied lines:

p

Save the changes

:w

Return to Original File:

:e#