Search and replace recursively on a UNIX-like system — using perl

Dec. 30th, 2007 | 01:22 am

In response to Nirav's example, I would like to share my way of doing a recursive search-and-replace operation on a UNIX-like system (OS X, GNU/Linux, etc.) using perl.

find . -type f -exec perl -wpi~ -e 's/hello/hi/g' {} \;

This will replace all occurrences of the string "hello" with the string "hi" in all files in the current directory. The "~" following the i switch is the suffix for the backup file name -- it's a good idea to let perl make a backup before modifying the original file.

If all goes well, you can delete the backups using the following command (run from the same directory):

find . -name *~ -exec rm -v {} \;

If you followed the first command, you can figure that this deletes all files ending with "~".

And if on examination you find that the first command didn't yield the desired results, you can revert your changes by running the following:

find . -type f \! -name *~ -exec mv -v {}~ {} \;

Magic? Read the manual, baby!

Link