Home > Linux, Tips & Tricks > Using vi to replace a string in multiple files

Using vi to replace a string in multiple files

August 9th, 2008

Sometime you may want to replace occurences of a string across multiple files.

There is an easy way to do so with the help of the vi editor.

This example will illustrate the power of vi:

Suppose you have 100 .html files, and you want to replace the occurence of the string ‘2007′ with ‘2008′.

As such, execute the following at your prompt:

vi *.html

This will open all the files ending with ‘.html’ in your current working directory. Then issue the following command:

:argdo %s/2007/2008/g | wq

That’s it! the above command will loop over each file, replacing (%) the word 2007 with the word 2008 globally (g) then it will save each file (w) and exit from it (q).

Note that the string to find and the string to use for replacement can be replaced with regular expressions. For instance, a caret (^) refers to the start of a line, the dollar sign ($) refers to its end, etc. So if we were to replace any line starting with ’sample’ and ending with ‘test’, one could use:

:argdo %s/^sample.*test$/g | wc

where .* matches anything in between the two string.

Note too that you may do the find and replace action without respect to the case (i.e. a search for ‘word’ will match ‘WoRd’). For that matter, simply replace ‘/g’ with ‘/gi’

Linux, Tips & Tricks

  1. mike
    August 23rd, 2008 at 12:24 | #1

    it’s caret, not carrot!

  2. admin
    August 29th, 2008 at 03:43 | #2

    Must have been thinking about food when typing it :)
    Cheers

  1. No trackbacks yet.