Howto Replace multiple file text string in Linux
Posted by Admin on August 13th, 2007
If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!
grep -R –files-with-matches ‘OLDSTRING’ . | sort | uniq | xargs perl -pi~ -e ’s/OLDSTRING/NEWSTRING/’
Where OLDSTRING is the string you want to find and replace with NEWSTRING.


August 13th, 2007 at 3:43 pm
Not sure why you run uniq on it, grep is perfectly capable of only returning unique results… And use the short options please. This should do just fine:
$ grep -rl OLDSTRING . | xargs perl -pi~ -e ’s/OLDSTRING/NEWSTRING/’
and if you want to do it sorted, files (this will even do unique results too!):
$ grep -rl OLDSTRING . | sort -u | xargs perl -pi~ -e ’s/OLDSTRING/NEWSTRING/’
and for you old school sed peeps (sed args aren’t as obscure):
$ grep -rl OLDSTRING . | xargs sed -i -e ’s/OLDSTRING/NEWSTRING/’
In all of these cases, you can replace the grep command with `find . -type f`. I’m guessing this hasn’t been performance tested. I’m also guessing for large files, just running the search and replace would be faster than scanning the file for matches, then scanning the file for matches AND replacing them.
August 29th, 2007 at 8:17 pm
In 1600 files want to replace the strings “text: ” by nothing, so i give the command
$ grep -R -l ‘text: ‘ . | sort | uniq | xargs perl -pi~ -e ’s/text: ‘//’
and then Ubuntu Feisty says
Unrecognized character \xE2 at -e line 1.
xargs: perl: exited with status 255; aborting
how to proceed?
September 1st, 2007 at 11:56 pm
daniel:
You’ll get that error if you copy and paste the line from your web browser because the single quote character that is pasted isn’t the same that you would type. Just delete the ’s from the command and type them back in manually. Also, it appears that you might have an extra ‘ just before the //’ at the end of your command.
I used James’ version, retyping the single quotes, and it ran perfectly, thanks!
August 13th, 2008 at 12:57 am
James’s solution works excellent for me
Thanks a lot!
July 30th, 2009 at 8:46 pm
1. $grep -R –files-with-matches ‘OLDSTRING’ . | sort | uniq | xargs perl -pi~ -e ’s/OLDSTRING/NEWSTRING/’
2. $ grep -rl OLDSTRING . | xargs perl -pi~ -e ’s/OLDSTRING/NEWSTRING/’
I tried both the options, but no use, i am on Linux4 63 bit.
please let me know how to proceed !
Thanks to ALL
November 18th, 2009 at 5:22 pm
James’ solutions don’t work if your directories have space in their names.