How to Find and Replace Text in Vim or Vi

How to Find and Replace Text in Vim or Vi
How to Find and Replace Text in Vim or Vi

Find and Replace Text in Vim or Vi

Vim is one of the popular text editors among the software developers & system administrators. The macOS as well as on different Linux Distros Vim comes preinstalled. We can edit code in Vim easily by using the different shortcuts. In this tutorial, you are going to learn How to Find 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/REPLACE/COMMAND_FLAG

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

You can also Find and Replace text for specific line number range using the following syntax:

:RANGE_FROM,RANGE_TO s/SEARCH/REPLACE/COMMAND_FLAG

Where,
RANGE_FROM: Find and Replace starts from this line number.
RANGE_TO: Find and Replace stops at this line number.

Examples of Find and Replace in Vim

We are going to take the following text for Find and Replace operations:

# Mount the partitions
sudo mount -o remount,uid=1000,gid=1000,rw /dev/sda6
sudo mount -o remount,uid=1000,gid=1000,rw /dev/sda7
sudo mount -o remount,uid=1000,gid=1000,rw /dev/sda8
sudo mount -o remount,uid=1000,gid=1000,rw /dev/sda9

First, If you are in any other mode then come to Normal Mode by typing Esc key.

1. Find and Replace Words with Another Word

You can replace all the occurrence of the word mount with unmount using below command:

:%s/mount/unmount/g

The output should be:

"How

2. Find and Replace Case-Sensitive Words with Another Word

To replace case-sensitive words you can use i flag. The following command will replace all case-sensitive occurrence of the word mount with unmount

:%s/mount/unmount/gi

The output should be:

"How

3. Find and Replace Words Between Specific Lines Range

You can also find and replace words between specific line numbers range. In the below example it will replace all the occurrence of the word sudo by root from line number 2 to 4 only.

:2,4 s/sudo/root/g

The output should be:

"How

4. Find and Replace Words with Confirmation

You can also ask for confirmation using the c flag. To ask for confirmation before replace you can use the following command:

:2,4 s/sudo/root/gc

The output should be:

"How

Conclusion

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here