≡ Menu

Vi / VIM: Find And Replace All Text Substitute Command

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. It is used for search and replace text.

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

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

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

To find and replace all occurrences of ‘eth1’ with ‘br1’, enter:
:%s/eth1/br1/g

To find and replace all occurrences of ‘eth1’ with ‘br1’, but ask for confirmation first, enter:
:%s/eth1/br1/gc

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. To find and replace all occurrences of ‘eth1’ with ‘br1’ for lines from 3 to 7, enter:
:3,7s/eth1/br1/g

A quick demo

Animated gif 01: Vim Find and Replace Demo

Animated gif 01: Vim Find and Replace Demo

Sysadmin because even developers need heroes!!!

Share this tutorial on:
{ 6 comments… add one }
  • Antonio February 26, 2014, 3:37 am

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

    • laike9m March 7, 2014, 8:12 am

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

  • Mehrad November 24, 2015, 2:19 am

    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 November 24, 2015, 2:26 am

    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 in Wikia:
    http://vim.wikia.com/wiki/Find_and_Replace

    cheers;

  • akd12345 April 12, 2016, 3:11 pm

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

  • Nadav Kavalerchik July 7, 2016, 1:30 pm

    Thanks!

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: