VIM Find And Replace All Text Substitute Command

See all VI / Vim text editor related FAQs/HowTos
I am a new Linux user. I started to use vim or vi text editor. How do I find all occurrence of the word called ‘eth0’ and replace it with ‘br0’ on Linux operating systems?

Both vi and vim text editor provides the substitute command called %s/SEARCH/REPLACE/flags. It is used for find/search and replace text. This page explains how to use substitute command for finding and replacing text with vim/vi.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux or Unix terminal
Category Text Editor
OS compatibility AIX AlmaLinux Alpine Amazon Linux Arch BSD CentOS Debian Fedora FreeBSD HP-UX Linux macOS Mint NetBSD OpenBSD openSUSE Pop!_OS RHEL Rocky Stream SUSE Ubuntu Unix WSL
Est. reading time 5 minutes

VIM Search and replace syntax

The syntax is as follows:
:%s/Search/Replace/CommandFlag
:%s/Search-Word/Replace-Word/g
:%s/Search-Word/Replace-Word/g
:%s/Search-Word/Replace-Word/gc
## Search and replace in the current line only ##
:s/Find-Word/Replace-Word/gc
## Change each 'Unix' to 'Linux' for all lines from line 36 to line 42 ##
:36,42s/Unix/Linux/g

VIM Find And Replace

Both vi and vim provides the :s command for search and replace. Let us see some easy to understand examples.

Examples

I am going to use the following sample text file:

-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
 
## full acess to lo and eth0 ##
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
-A INPUT -i eth0 -j ACCEPT
-A OUTPUT -o eth0 -j ACCEPT
 
# log spoof
-A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP DROP SPOOF A: "
-A INPUT -i eth1 -s 10.0.0.0/8 -j DROP
 
-A INPUT -i eth1 -s 172.16.0.0/12 -j LOG --log-prefix "IP DROP SPOOF B: "
-A INPUT -i eth1 -s 172.16.0.0/12 -j DROP

VIM search and replace using the substitute command in a single line

To find each occurrence of ‘eth0’ in the current line only, and replace it with ‘br0’, enter (first press Esc key and type):
:s/eth0/br0/g

VIM replace all occurrences

Next try to find and replace all occurrences of ‘eth1’ with ‘br1’ under vim, enter:
:%s/eth1/br1/g
The % symbol is prefixed to replace all occurrences in each line.

Vim find and replace all but with confirmation

Search and replace all occurrences of ‘eth1’ with ‘br1’, but ask for confirmation first on vim, enter:
:%s/eth1/br1/gc
Add c option at the end of the search and replace command prompt you before a replacement is made. So, when you type :%s/eth1/br1/gc, you will get confirmation prompt as follows:

replace with br1 (y/n/a/q/l/^E/^Y)?

Press y for yes, n for no, and a for all occurrences. You can also press q to quit, l for only one line. Also, pree CTRL-E (^E) to scroll the screen up and CTRL-Y (^Y) to scroll the screen down.

Case sensitivity

To find and replace all occurrences of case insensitive ‘eth1’ with ‘br1’, enter:
:%s/eth1/br1/gi
The above example will find eth1, ETH1, eTh1, ETh1 and so on and replace with br1. In other words, we passed i flag to ignore case for the search pattern.

Search Range

By default, when no range is defined, the vim substitute command works only in the current line. The range is typically between two lines, and the syntax is:
start,end
10,20

Let us find and replace all occurrences of ‘eth1’ with ‘br1’ for lines from 3 to 7, enter:
:3,7s/eth1/br1/g
The range is inclusive. In this following example, change each ‘eth3’ to ‘br0’ for all lines from the current line (.) to the last line ($) inclusive:
:.,$s/eth0/br0/g
We can also tell vim about the next few lines using a range. For instance, let us change each ‘eth0’ to ‘br0’ for the current line (.) and the two following 13 lines:
:.,+13s/eth0/br0/g
In our final example, I will change each ‘br0’ to ‘bridge0’ in each line, starting with ‘config’.
:g/^config/s/br0/bridge0/g

Using different character instead of / when finding and replacing in Vim / Vi

Instead of the ‘/‘ which surrounds the pattern and replacement string, you can use any other single-byte character, but not an alphanumeric character, ‘\‘, ‘"‘ or ‘|‘. This is useful if you want to include a ‘/‘ in the search pattern or replacement string. For example:
:s+/+//+
Find ‘/usr/bin/ and replace with /usr/sbin/, then:
:s+/usr/bin/+/usr/sbin/+g
OR work on the whole script named update.sh:
:%s+/usr/bin/+/usr/sbin/+g

A quick demo

Animated gif 01: Vim Find and Replace Demo

Animated gif 01: Vim Find and Replace Demo

Substitute syntax

The full syntax is as follows:
:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
So for each line in [range] replace a match of {pattern} with {string}. A {pattern} is one or more branches. A {string} can be a literal string. When [range] and [count] are omitted, replace in the current line only. When [count] is given, replace in [count] lines, starting with the last line in [range]. When [range] is omitted start in the current line. The [count] must be a positive number. If the {string} part is omitted, the matched pattern is deleted. The following find and replace in Vim / Vi deletes all instances of the string ‘iPhone3GS’ in the current line:
:s/iPhone3GS//g
To remove ‘iPhone3GS’ from whole file, run:
:%s/iPhone3GS//g

On each line, delete all occurrences of the whole word “Sysadmin”

Yes, we can delete words too:
:%s/\<Sysadmin\>//g

How can I delete the first occurrence of the whole word “method_” and the following 3 characters?

:%s/\<method\>.\{3}//

Search and replace current line only

Find each occurrence of ‘bin’ in the current line only, and replace it with ‘sbin’ in wrapper.sh:
:%s/bin/sbin/gc

Some common examples to find and replace in Vim / Vi

Replace all instances of ‘CentOS’, ‘RHEL’, ‘Ubuntu’, ‘Fedora’ and ‘Arch’ with ‘Linux’:
:%s/CentOS\|RHEL\|Ubuntu\|Fedora\|Arch/Linux/g
Now try to replace all instances of ‘CentOS’, ‘RHEL’, ‘Ubuntu’, ‘Fedora’ and ‘Arch’ with ‘GNI/Linux’ using + as the search pattern:
:%s+CentOS\|RHEL\|Ubuntu\|Fedora\|Arch+GNU/Linux+g
Want to add comments from line 40-49, try:
:40,49s/^/#/
On the other hand, we can uncomment lines from 7 to 42:
:7,42s/^#//
In this example, replace the last occurrence of “FreeBSD” with “OpenBSD”.
:%s/.*\zsFreeBSD/OpenBSD/
Next, we are going to delete all occurrences of the whole word “addUser”.
:%s/\<addUser\>//g
On each line, delete the first occurrence of the whole word “delUser” and the following 21 characters.
:%s/\<delUser\>.\{21}//
Let us change each ‘modifyUser’ (case insensitive due to the i flag) to ‘modifyUsers’ and ask for confirmation too:
:%s/modifyUser/modifyUsers/gci

Conclusion

You learned how to find and replace text with vi or vim text editor using the %s substitute command. Type the following command inside vim to get help about substitute topic or see documents:
:help :substitute

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

9 comments… add one
  • Antonio Feb 26, 2014 @ 3:37

    Is a good aportation i´m a mexican student
    how to replace worlds after cursor

    • laike9m Mar 7, 2014 @ 8:12

      cursor? I think you only have one cursor so why not do it manually?

    • Sam Oct 27, 2020 @ 21:14

      Antonio, you can replace the word after the cursor with `cw` (change word) or, if your curso is in the word, but not at the begining of the word you can use `ciw` (change internal word).

  • Mehrad Nov 24, 2015 @ 2:19

    what about skipping characters?
    I have ../aaa/ and I want to replace it with bbb/
    I tried the following but it didn’t work:
    :%s /..\/aaa\//bbb\//gc

  • Mehrad Nov 24, 2015 @ 2:26

    Hi

    forget about my previous command, it was a upper case mistake, but please mention using other delimiters and character skipping in your post. I found them below:
    http://vimdoc.sourceforge.net/htmldoc/change.html#:substitute

    cheers;

  • akd12345 Apr 12, 2016 @ 15:11

    A vote of thank !!! 🙏
    :%s/search/Replace/gic works for me

  • Nadav Kavalerchik Jul 7, 2016 @ 13:30

    Thanks!

  • Ankit Apr 26, 2017 @ 8:41

    If one line contain two identical words and i want to replace only one word which i want,
    Which command is use?

  • Enis Ilkin Jun 7, 2021 @ 8:55

    Find and replace in Vim / Vi is easy. For example, to search for the first occurrence of the string ‘data’ in the current line and replace it with ‘delta’
    :s/data/delta/
    To replace all occurrences of the search pattern, add the g flag in the current line:
    :s/data/delta/g
    For entire file:
    :%s/data/delta/g

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.