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’
Awsome! Worked for me. Thanks
Awesome tip. Thank you so much for sharing came in life saver when had edit over 200 files.
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.
I always appreciate individuals who discuss creativeness with us thanks for the publish keep published and create me comprehend more.
Thanks dude !!! Saved a lot of headache !!!
wow.. worked like a charm..
thanks guys! this tip is a lifesaver.
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
Thanks for this hint, you saved me a bunch of work with that.
Must have been thinking about food when typing it
Cheers
it’s caret, not carrot!