Find & Replace Text in Multiple Documents from the Command Line
If you’re comfortable with the command line and ever in a situation where you need to find and replace a word, phrase, URL, or character across a group of multiple text documents, perl does the job quite well. A simple command string will very quickly perform a group batch find and replace on text, whether in a single document or spanning a group of multiple documents.
Like many things in the command line, there is no confirmation process, so you’ll want to make sure your syntax is set correctly before initiating a command, otherwise you may need to do another find & replace to repair your typo.
The basic command syntax is as follows:
perl -pi -w -e 's/THIS/THAT/g;' /path/to/files*.txt
For a single word example, if you need to replace all instances of “ogre” with “cornbread” in every .txt file within the “Documents” folder, then you would use the following command:
perl -pi -w -e 's/ogre/cornbread/g;' ~/Documents/*.txt
For an example of finding and replacing an entire phrase, let’s assume we’re going to replace the entire sentence “The Chocolate Factory” with “The Wizard of Oz” in a group of .txt files starting with “Films” stored in the Documents directory:
perl -pi -w -e 's/The Chocolate Factory/The Wizard of Oz/g;' ~/Documents/Films*.txt
The find and replace is done immediately. You can double-check the change by using cat and grep to check:
cat ~/Documents/Films124.txt |grep "Wizard of Oz"
Admittedly, this is fairly advanced, and yes, batch find and replace through multiple documents can be done in a more user friendly fashion through GUI apps like TextWrangler and BBEdit, but sometimes the command line is just faster for quick tasks like this and others that are similar, plus it doesn’t require any additional downloads to use.
A big thumbs up to Lifehacker for the excellent trick.
Update: The ‘sed’ command is another way of doing quick find and replace through the command line. Covering sed is mostly a topic for another article, but the basic syntax of using sed for this task is a bit simpler and thus easier to remember:
sed -i 's/THIS/THAT/g' /path/to/files*.txt
There is no right or wrong way, so whether you use perl or sed becomes a matter of personal preference.