CentOS

How to Replace All Matches of a Search Text in VI Editor

The VI editor or the Vim editor is another powerful cross-platform text editor. It comes with different modes for running the commands and text editing. It also provides all the latest features that you can find in any good text editor including text search, text replacement, etc. Once you learn its different modes of operation, it will be very easy for you to use the VI editor. In this guide, we will discuss about the steps on how we can replace all the occurrences of a given search text with another using the VI editor.

How to Replace All the Matches of a Search Text in the VI Editor

If you ever want to replace all the occurrences of any given word in a text file using the VI editor, you can follow the process explained in the following steps:

Step 1: Open the Target File with the VI Editor

First, you should open the text file in which you want to make the replacement. For that, we use the following command:

$ sudo vi sample.txt

Replace the “sample.txt” with the name of that specific text file in which you want to make the replacement.

Our target text file is shown in the following image:

Step 2: Run the Relevant Command to Replace All the Matches of a Search Text in the VI Editor

We replace all the occurrences of the word “Hello” within our text file that is shown previously with the word “Bye”. For that, we will use the following command while staying within the command mode of the VI editor:

:%s/Hello/Bye/g

After running this command, we instantly witnessed the changes within our text file as shown in the following image. Moreover, the VI text editor also explicitly specified the total number of substitutions that took place as a result of executing this command.

Step 3: Save the Target File

By now, you will be sure that all the matches of the specified search text are successfully replaced. After making these changes, you need to save them and execute the following command:

:x

This command simply saves your text file and lets you exit the VI editor.

Step 4: Recheck the Target File for Confirmation

Now, if you want to recheck the target file for the confirmation of the changes, you can open it again with the VI editor as explained in the first step. The following image confirms that all the occurrences of the specified word is replaced successfully:

Conclusion

By learning the method explained in this article, you will conveniently be able to replace all the occurrences of your desired text within a file by using the VI editor. All you need is to have the VI editor installed on your operating system. Apart from that, you need to have a basic know-how of its different modes. After which, you will instantly be able to follow this procedure.

 

Similar Posts