Monday, July 9, 2012

Find and Replace Strings in Linux with Grep and Sed

It would be very useful if we can find a string in multiple files and replace it with a new string. It takes a single line of code to do that :

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

matchString - the string you want to find
string1 - same string you want to find
string2 - new string that you want to replace with


eg :
I need to find the string "foo" and replace it with "bar"

grep -rl 'foo' ./ | xargs sed -i 's/foo/bar/g'  

 There is a nice post on describing more on this:
http://vasir.net/blog/ubuntu/replace_string_in_multiple_files/