How to Search and Replace Text in Vim or Vi

Table of Contents
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.
LATEST POSTS
-
How to Install Kodi on Ubuntu 18.04
-
How to Set Up Cron Job on CentOS 8
-
How to Install Grub Customizer on Ubuntu 18.04 LTS Linux
-
How to Install DataGrip on Debian 10
-
How To Secure Nginx with Let’s Encrypt SSL on Debian 10
-
How to install Dropbox on Debian 9 Server and Desktop
-
How To Check Ubuntu Version
-
How to Install Yarn on Ubuntu 18.04
-
How to Install XAMPP on Linux Mint 19
-
How to Install Netbeans on Ubuntu 18.04
-
How to Install WebStorm on Linux Mint 19
-
How to Install Google Chrome on Ubuntu 19.04