How to Search and Replace Text in Vim or Vi


Find and Replace Text in Vim or Vi

Vim is a popular text editor among the system administrators and developers. On most of the Linux Distros, it comes preinstalled. We can edit code in Vim easily by using the different shortcuts. In this tutorial, you are going to learn how to Search and Replace Text in Vim or Vi.

Basic Syntax for Find and Replace in Vim

Following is the basic syntax for Find and Replace in Vim:

:%s/SEARCH_TEXT/REPLACE_TEXT/COMMAND_FLAG

In the above syntax,
SEARCH_TEXT: Text to search.
REPLACE_TEXT: Text to replace.
COMMAND_FLAG: Different flags used when search and replace.

1. Search and Replace Words in Current

You can replace all the occurrence of the specific word on the current line using below command:

:s/SEARCH_TEXT/REPLACE_TEXT/g

 

2. Search and Replace Words on All Lines

You can replace all the occurrence of the specific word on all the lines using below command:

:%s/SEARCH_TEXT/REPLACE_TEXT/g

3. Search and Replace Case-Sensitive Words

By using the i flag we can replace case-sensitive words. You can use following command to Search and Replace Case-Sensitive words.

:%s/SEARCH_TEXT/REPLACE_TEXT/gi

4. Search and Replace Words Between Specific Lines Range

You can also search and replace words between the specific line number range by using the following command:

:RANGE_STARTS_AT,RANGE_STARTS_AT s/SEARCH_TEXT/REPLACE_TEXT/g

4. Find and Replace Words Asking Confirmation

 

By using the c flag we ask for confirmation before replacing text.

:%s/SEARCH_TEXT/REPLACE_TEXT/gc

 

Conclusion

In this tutorial, you have learned how to Search and Replace Text in Vim or Vi. If You have any queries regarding this please comment below.