Finding and replacing text in a single text file is simple, you can use the Find and Replace function within the edit menu of your text application. The problem arises is want to use this feature in many text files. You can open each one, but that is a little complicated. Today we are going to adapt a script within terminal to carry out this command on a set of text files within a folder. It will open each text file, search for the exact or partial string and then replace it with the text we want. This is a little complicated but a great time saver.
Bulk Find and Replace
The first step is to open up Terminal. We are going to use a terminal command. The first thing is to navigate to the folder with the text files we wish to edit. To do this type the following, note that terminal starts in your user directory so if you want to navigate to a folder type the following:
This will navigate to a folder on your desktop, aptly named ‘folder’.
The script we are going to run is the following, modified from stack exchange:
perl -pi -e 's!find!replace!g;' *.txt
This will run a perl script to find the exact phrase, in this case ‘find’ and replace it with ‘replace’. It will replace an exact phase as found between the exclamation points. This can extend to urls as well, pretty much any complex phase as long as it doesn’t have an exclamation point. The *.txt will mean it will try and run the replace command on any text file it can find within the folder.
perl -pi -e 's!http://www.example.com!http://www.mactricksandtips.com!g;' *.txt
Replace Part Of A Word
If you want to replace a part of a word you use forward slashed instead. For example, this will replace every instance of the letters ‘abc’ with ‘efg’. This will replace letters within words.
perl -pi -e 's/abc/efg/g;' *.txt
If the text you are trying to replace contains a forward slash, quote or double quote ensure you escape the character with a backward slash. This ensures the letter is treated correctly. In this case a forward slash will be replaced.
perl -pi -e 's!\/!character!g;' *.txt
If you want to replace text within one file, use the file name instead of a star. The start will run the command in any file it finds.
perl -pi -e 's!find!replace!g;' filename.txt
If you want to run this command on other text files, as long as they open correctly within TextEdit you can. For example .eml email files work correctly as well.