Sunday, August 7, 2011

Batch text replace (using grep and sed to replace all occurances of a string in all files recursively through directories)

Easy enough, just grep for the string, and pass the returned file list into sed using xargs. But what about the details?

This site was my best hit on google using the obvious search:

http://stackoverflow.com/questions/1169927/using-sed-and-grep-to-search-and-replace

I used a slighly different set of arguments when I did it, since egrep seems like a royal pain for my purposes. I added a -t to my xargs call so I could monitor what it did each time it did it:

grep -l oldstring *.* | xargs -l -t sed -i -e 's/oldstring/NEWSTRING/g'

Here's a version using find that worked for me:

$ find . -name "*.htm" | xargs -l -t sed -i -e 's/oldstring/NEWSTRING/g'

Here's a novel way to just search for the files that have the string. Might be interesting to find a way to link this up with xargs for the substitution. Not sure what the extra backslash is about:

find . -exec grep -l “string to find” {} \;