Tuesday 9 April 2013

Unix: VI search and replace command examples



Let us say you would like to find a word called "foo" and replace with "bar".

First hit [Esc] key

Type : (colon) followed by %s/foo/bar/ and hit [Enter] key.
:%s/foo/bar/

Above command will replace first occurrence of word foo with bar on all lines. The % is shorthand for all lines.

To replace all occurrences of word foo with bar on all lines, use the g option (which indicates all occurrences on a line).
:%s/foo/bar/g

Note that the g can be replaced with a number 1,2,...N to change only the n'th occurrence on each line.

Use find and replace on line ranges (match by line numbers)

You can also make changes on range of lines i.e. replace first occurrence of foo with bar on lines 5 through 20 only, enter:
:5,20s/foo/bar/

Following command will replace first occurrence of foo with bar starting at the current line for the next 100 lines:
:.,+100s/foo/bar/

Match by words

Finally, you can match by words i.e. replace first occurrence of foo with bar starting at at the next line containing a word "test":
:/test/s/foo/bar/g

As usual you can specify ranges:
:/test/,/guest/s/foo/bar/g

Please note that all search/replace commands should be start with the [ESC]: keystroke combination onl

No comments:

Post a Comment

Number of Visitors