Multiple File Search and Replace
Since I started using a CLI on a regular basis 7 years ago I’ve used a Perl script that looped over a list of files and executed a regular expression replace on each line of the input files for search and replace. I recently found out that Perl has command line options to make this exceptionally easy, and as a result I no longer need my search and replace script.
The solution uses the -p, -i and -e options to Perl. Perl’s -p options will run the supplied script on every line of input. The -i tells per to use a supplied list of files as input and edit them in place. A file extension can follow the -i option to save backup files. The -e allows you to supply the script to execute on the command line. An example of using this is:
perl -p -i.bak -e 's/foo/bar/g' *.txt
This will replace all occurrences of foo with bar in all files with the extension .txt and save a backup copy of each file to filename.txt.bak.
You can get more elaborate with the script you are supplying to -e by providing multiple lines separated by semicolons or use multiple -e commands. You are also not limited to executing a regular expression, you can do far more complicated things, but thats beyond this ‘quick scripts’ entry.
One handy command to use in conjunction with the Perl multiple file search and replace is rename which will help when you want to undo the changes you just made. To undo the changes made in the above example you would run:
rename .bak '' *.txt.bak
Which will covert the string .bak to an empty string in the list of filenames supplied. So, filename.txt.bak gets renamed to filename.txt, replacing your modified files with the backups that were made.
So, go forth, search and replace!