Shell Magic: Globally Find/Replace Text Using RegExps Within Many Files

Here’s one of my favorite Perl-based one-liners which I whip out when I need to find a bunch of files and replace text based on regular expressions at the command line.

find . -iname ‘*.js’ -exec perl -pi.bak -e ‘s/2006/2007/g’ {} \;

This example first finds all JavaScript files (using a case-insensitive file extension) in the current directory. Each file is then parsed. If the string “2006” is found within the file, it is backed up to a file of the same name with a “.bak” extension, after which all occurances of “2006” are replaced with “2007”. w00t!

Leave a Reply

Your email address will not be published. Required fields are marked *