Junk Food for the Brain

Open Source and Awesomesauce :)

How to Search and Replace in Vim

| Comments

Just for reference, may help other people. Searching for text and replacing in vim is an invaluable skill, which helps sysadmins during the conf. file troubleshooting.

For example, assume you have this /etc/hosts file with a list of machines that are numbered sequentially. For some insane reason, some dude suggests a now naming scheme. Replacing 10 or 15 lines manually is a pain, not to mention error prone.

192.168.0.1 node01
192.168.0.2 node02
192.168.0.3 node03
192.168.0.4 node04
192.168.0.5 node05
192.168.0.6 node06

Now, your resident office genius decides that the names for these machines should be cluster-nodexx instead of nodexx. Great, now imagine having 200 machines in your hosts file. No way you’re going to manually edit that by hand. This is where vim’s search & replace function comes in handy.

First, open the file in vim:

# vim hosts

Now, to replace the the word node with cluster-node, press the colon “:” to enter command mode an type the following:-

:%s/node/cluster-node/gc

Lets break down the command.

  • %s : instructs vim to search
  • /node/: The words within the first two forward slashes are the characters vim will search for
  • /cluster-node/: The words between the second and third forward slashes are what vim will replace node with.
  • g: after the thrid forward slash, the ‘g’ stands for global. Without this, vim will only replace the first occurrence of the word node.
  • c: ‘C’ will make vim prompt you for confirmation before replacing the word. Very handy especially when editing source or configuration files.
  • Here’s an example of how this would look like: vim-search_n_replace
    Note the highlighted matches, and the prompt below asking for your confirmation.

This should help you do some mass replacing with ease.