Vim – Find and replace strings

Vim can be hard to use at the beginning, but when you’re used to it and know a few tricks, it’s impossible to go back to nano, also known as ‘the text editor for kids’.

You need, for instance, replace all the occurrences of the ip 10.0.0.10 by 10.0.0.11 in a configuration file :

1 – Open your file with vim

vi /etc/service/configuration.conf

2 –  Type the following (don’t forget to stat with “:”) :

:%s/10.0.0.10/10.0.0.11/g

What the command exactly did ? %s is of substitution and g for global, meaning you will replace all the occurrences.

But what if you configuration file contains 10.0.0.105 ?

With the previous example, 10.0.0.105 will become 10.0.0.115 and that’s not what we want !

To avoid partial match you have to execute the following :

:%s/\<10.0.0.10\>/10.0.0.11/g

The command will replace only 10.0.0.10 and not 10.0.0.105 because we searched for the full word only.

 

 

Leave a Reply

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