Walker News

How To Get Vi Search And Replace Interactively?

It’s not easy to learn vi, especially to those who spend more times on Microsoft Windows than Linux/UNIX. Once get used to it, however, people just love vi naturally :)

Assuming you’ve basic idea of how to use vi editor (e.g. press ESC key each time before execute vi command), here are some of the vi tricks that are useful for search and replace targeted text.

To search and replace all occurrences of a search text called pattern throughout the edited file with new text called sign:
:%s/pattern/sign/g

To change all occurrence of “pattern”, in line 3 to line 5 only, to “sign”:
:2,5s/pattern/sign/g

Sometimes, it’s useful to search and replace text interactively, i.e. get vi to ask for confirmation before replace each of the searched text. To do this, just use the “c” (shorts for confirmation) in the substitute command of vi editor:
:%s/pattern/sign/gc

Then you’ll see a prompt at bottom of vi editor similar to this:
replace with sign (y/n/a/q/l/^E/^Y)?

To replace, just press y. Otherwise, press n to ignore / skip replacement (for some of the searched text).

NOTE, all the above examples do not distinguish “patterns” and “pattern”. If you expect it to replace the exact word called “pattern” only (ignore variances like “patterns” or “the_pattern”, etc), then make sure the search text is enclosed by \< and \>, e.g.:
:%s/\<pattern\>/sign/g

So, there are only four key points to remember for search and replace function using vi editor.

Custom Search

2014  •  Privacy Policy