Home > System Administrator's Guide > Powerful Find and Replace Examples For VI Editor – Part 2

Powerful Find and Replace Examples For VI Editor – Part 2

September 8th, 2009

Substitute either word1 or word2 with a new word using regular expression

In the following example, it will translate any occurrences of either good or nice will be replaced with awesome.You can also do substitution by specifying regular expression.

Original Text: Linux is good. Life is nice.
:%s/\(good\|nice\)/awesome/g
Translated Text: Linux is awesome. Life is awesome.

Following example does the substitution of hey or hi to hai. Please note that this does not do any substitution for the words ‘they’, ‘this’.

:%s/\<\(hey\|hi\)\>/hai/g
  • \< – word boundary.
  • \| – “logical or” (in this case hey or hi)

Interactive Find and Replace in Vim Editor

You can perform interactive find and replace using the ‘c’ flag in the substitute, which will ask for confirmation to do substitution or to skip it as explained below. In this example, Vim editor will do a global find the word ‘awesome’ and replace it with ‘wonderful’. But it will do the replacement only based on your input as explained below.

:%s/awesome/wonderful/gc
replace with wonderful (y/n/a/q/l/^E/^Y)?
  • y – Will replace the current highlighted word. After replacing it will automatically highlight the next word that matched the search pattern
  • n – Will not replace the current highlighted word. But it will automatically highlight the next word that matched the search pattern
  • a – Will substitute all the highlighted words that matched the search criteria automatically.
  • l – This will replace only the current highlighted word and terminate the find and replace effort.

Substituting all lines with its line number.

When the string starts with ‘\=’, it should be evaluated as an expression. Using the ‘line’ function we can get the current line number. By combining both the functionality the substitution does the line numbering of all lines.

:%s/^/\=line(".") . ". "/g

Note: This is different from the “:set number” where it will not write the line numbers into the file. But when you use this substitution you are making these line number available inside the file permanently.

Substituting special character with its equivalent value.

Substituting the ~ with $HOME variable value.

Original Text: Current file path is ~/test/
:%s!\~!\= expand($HOME)!g
Translated Text: Current file path is /home/ramesh/test/

You can use expand function to use all available predefined and user defined variables.

Comments are closed.