Unix Tutorial : vi tutorial -2

Last updated on November 12th, 2016 at 05:55 am

Here we would be continuing our series on Vi editor learning. We have learned about how to open file using vi editor, how to edit it in the below link

Unix Tutorial :vi editor Part -1

Now we would be seeing vim search command, vi substitution, vi replace with examples


vim search command

/string Search forward for string like error
?string Search back for string
n Search for next instance of string
N Search for previous instance of string
% Searches to beginning of balancing ( ) [ ] or { }
?str Finds in reverse for str
:set ic Ignores case when searching. Suppose you want to search for failure ,now we dont the case it will happen,so setting this will help in finding all the occurence
:set noic Pays attention to case when searching
:n,ms/str1/str2/opt Searches from n to m for str1; replaces str1 to str2; using opt-opt can be g for global change, c to confirm change (y to acknowledge, to suppress), and p to print changed lines
& Repeats last :s command
:g/str/cmd Runs cmd on all lines that contain str
:g/str1/s/str2/str3/ Finds the line containing str1, replaces str2 with str3
:v/str/cmd E xecutes cmd on all lines that do not match str

Examples of vim search command

A file x.txt is given ,we do below search strings on it

/fmw_home search forward for fmw_home in the file
?fmw_home search backward for fmw_home in the file
n repeat previous search
N repeat search in opposite direction
/, ? repeat search forward or backward


It is a very function which is used in vi. Many times you have to replace certain field with other ,that time it is very useful

The search and replace function is accomplished with the :s command. It is commonly used in combination with ranges or the :g command (below).
:s/pattern/string/flags Replace pattern with string according to flags.
g Flag – Replace all occurences of pattern
c Flag – Confirm replaces.
& Repeat last :s command

It can be used like this also

Examples of Replace

:s^/oracle^/applmgr^g This will replace /oracle with /applmgr everywhere in the file
s,^a,^b, g This will replace ^a with ^b everywhere in the file
:2,8/this/s//that replace first occurrence of `this’ with `that’ in lines 2 through 8
:2,$/this/s//that replace first occurrence of `this’ with `that’ in lines 2 through the end
:g/\/home\/me/s//\/r2\/you/g replace /home/me with /r2/you throughout the file
: 33,224s/^/hh/ insert the string ‘hh’ at the beginning of lines
:%s/{TAB}*$// Strip blanks at end of line:

The last  part in the series is given below

vi tutorial part-3

Hope you like the content on vim search command, vi editor replace. Please do provide the feedback

Leave a Reply