Search and Replace on Multiple Files

Recently one of my hosting providers went and changed the path to my home directory without telling me.  So, I had to go through a gajillion files and modify a path to reflect the changes.  I thought I’d go ahead and share how I did that for anyone out there that has a similar need.

There are several ways to accomplish this – but this is how I like to do it (this is from a linux command shell):

find . -name somefile -exec perl -pi.bliki -e ‘s/textToFind/replacement/g’ {} \;

The above command uses the find command, starting from the current location (.), looking for files named ‘somefile’ (-name somefile), and every time it finds one, it runs the command following the -exec parameter.  The command following the -exec parameter is a perl one-liner that backs up the file it’s about to modify (with a .bliki extension, I just try to pick something I’m sure will not result in overwriting a legitimate file), and then does a global search and replace of textToFind with replacement.  In the above command, the {} is where find inserts the current file it has found.  You must backslash the semi-colon at the end so that the shell doesn’t interpret it and leaves it for use by the find -exec command.

Once you’ve completed the search and replace, you use the following command to go through and remove all of the backup files created with the .bliki extension.

find . -name somefile.bliki -exec rm {} \;

Hope this makes sense?

Post questions if you need clarification on anything.