This blog post describes how to search and replace string in vi editor.  vi or vim is a power full text editor comes with Linux/Unix based operating system.

Suppose we have a simple text file named as sample.txt. The contents of the sample.txt file is

I want to learn Linux.
Linux is open source operating system
Linux is more secure
Learning Linux is a good skill

how to search and replace string in vi editor

Now suppose we need to find all string (Linux) and replace with another string (Ubuntu). vi or vim editor comes with inbuilt commands.  To find all occurrence of string Linux and replace with string Ubuntu we need to use substitute command. The syntax of substitute command is

:%s/Linux/Ubuntu/g

Let us execute this command:

step 1) Open sample.txt file

#vi sample.txt

how to search and replace string in vi editor

Step 2)

Press Shift + : and write command %s/Linux/Ubuntu/g and hit enter button. This will replace all Linux with Ubuntu. To save the changes write :wq  command.

Read Some more tips

  • Replace the string only from current Line? use command :s/Linux/Ubuntu/g


Related Contents to follow