Using vi to replace a string in multiple files

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’

10 thoughts on “Using vi to replace a string in multiple files”

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>