Mass search and replace with sed and grep
Posted in programming, sed, tips on March 4th, 2010 by fseek – 2 CommentsEver had to search and replace a string in multiple files? That’s how to do it with grep and sed
Today at work I was tasked to upgrade the copyright statement on all our PHP, HTML and C files from 2009 to 2010. Plus, it had to be done only on the files that we owned the copyright. That’s how I did:
1- Search for all the files that we own the copyright
$ cd /source
$ grep -r “Copyright OurComapany Inc” *
It will print all files that match our copyright, so we know at least what files we are changing.
2- Search and replace all these files
$ grep -r “Copyright OurComapany Inc” * | cut -d “:” -f 1 | sort | uniq | xargs sed -i ’s/Copyright 2009/Copyright 2010/’
With this command, we will run “sed” to replace the string 2009 to 2010 on all the files that matched our copyright stement. If you wanted to replace all the files, just the following would work:
$ find ./ | xargs sed -i ’s/Copyright 2009/Copyright 2010/’
