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’

11 Responses to “Using vi to replace a string in multiple files”

  1. subhangi says:

    Awsome! Worked for me. Thanks

  2. Niall says:

    Awesome tip. Thank you so much for sharing came in life saver when had edit over 200 files.

  3. it business solutions says:

    I considered I would keep my first viewpoint. I do not know what to say. Awesome weblog website,I would keep watching this weblog website very often.

  4. low cost tubal reversal says:

    I always appreciate individuals who discuss creativeness with us thanks for the publish keep published and create me comprehend more.

  5. Deepanshu says:

    Thanks dude !!! Saved a lot of headache !!! :) :D

  6. thanks says:

    wow.. worked like a charm.. :)

  7. Himanshu says:

    thanks guys! this tip is a lifesaver.

  8. Than you very much says:

    Thanx a lot, it helped me too.

    I have a comment, for relatively small number of replacements, prompting for replace could also be useful.

    :argdo %s/search_string/replace_string/gc | wq

    with an additional ‘c’ for ‘confirmation’

    Thanks again :)

  9. Jens says:

    Thanks for this hint, you saved me a bunch of work with that.

  10. admin says:

    Must have been thinking about food when typing it :)

  11. mike says:

    it’s caret, not carrot!

Leave a Reply