How to Replace in Vim

· 379 words · 2 min

The substitute command can be used to perform basic to advanced search and replace functions with a single command. The syntax for this command is:

:s/<search_term>/<replace_term>/option

Where

Search and Replace in a single line

To search and replace the occurrence of a word only in a single line instead of the whole file, use the following syntax:

:s/<search_term>/</replace_term>/g

Search and Replace in a Whole File

To search and replace the occurrence of a word only in a single line instead of the whole file, use the following syntax:

:%s/<search_term>/<replace_term>/g

Search and Replace with Confirmation

If you want to be asked for confirmation before replacing the search term, use “c” at the end of the search command as follows:

:s/<search_term>/<replace_term>/gc

The above command will ask for confirmation before each replacement (Enter y for yes while n for no).

Case insensitive Search and Replace

When you perform search and replace in Vim, by default it is case sensitive. You can perform a case insensitive search by adding “i” at the end of command as follows:

:s/<search_term>/<replace_term>/gi

Search and replace the whole word

By default the substitute command search for any match whether it is partial or full. In order to match the exact search_term and then replace it with the replace_term, enclose the search _term within the \<\>.

For instance, in some documents, you want to search and replace the exact word “you” by “me”. In that case, the following command would be used:

:s/\<you\>/me/
   △△  △△

It will find the word “you” and replace it with “me”. However, it will not replace the words like “yours”.

Search and Replace Words among particular Lines

In order to search for a word among the particular lines instead of just one line or the whole file, the following syntax can be used:

:<start_line>,<end_line>s/<search_term>/<replace_term>/g

For instance, to search and replace the occurrence of Ubuntu with Debian from lines ranging from 3 to 8 in some file, the command would be:

:3,8s/ubuntu/debian/g
 △△△

To search and replace the occurrence of a word from the current line to the last line, the following syntax would be used:

:.,$s/<search_term>/<replace_term>/g
 △△△

In the above command, . stand for current line and $ stand for the last line.

Vim