Options in the search and replace command in vi editor

June 5, 2012

1. What is the difference between s/old/new/ and s/old/new/g ?

The g option at the end of the line will replace all occurrences of “old” in a particular line with “new”.

If the g option is not used only the first occurrence of “old” in a particular line will be replaced with “new”.

2. What is the use of the “c” option in the use caseĀ  s/old/new/gc ?

This option will ask for an affirmation or negation before every replacement is made.

3. What does this mean :g/some text/s/search text/replacement text/ ?
“for all lines containing `some text’, search for `search text’ and replace any instances with `replacement text.'”

4. What does this mean :g!/some text/s/search text/replacement text/ ?
“for all lines not containing `some text’, search for `search text’ and replace any instances with `replacement text.'”
It is the same as :v/some text/s/search text/replacement text/

Reference :

http://sunsite.uakom.sk/sunworldonline/swol-10-1997/swol-10-unix101.html


Substitute (Search and replace) command in the vi editor

June 5, 2012

1. How to replace an occurrence of “old_string” by “new_string” in a file

{code} :s/old_string/new_string/g{/code}

2. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines 1 to 10

:1,10s/old_string/new_string/g
3. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines 1 to the current line ?

The current line (where the cursor is located) can be specified as a single dot (.).

:1,.s/old_string/new_string/g

4. How to replace an occurrence of “old_string” by “new_string” in a file withinthe range of lines from the current line to the last line?

The last line can be specified as a dollar sign ($).

:.,$s/old_string/new_string/g

5. How do you search the whole file ?

:%s/old_string/new_string/g or
:1,$s/old_string/new_string/g
6. How can you execute a search and replace on the current line and the next five lines ?

The beginning or ending line for a range may be given as a positive or negative number of lines offset from the current line.

:.,+5s/old_string/new_string/g

7. How can you execute a search and replace from five lines above the current line through the current line ?

:-5,.s/old_string/new_string/g

8. How can you perform a search and replace from five lines above the current line through five lines below the current line ?

:-5,+5s/old_string/new_string/g