Easily Find And Replace Text Across Multiple Files
If you are stuck with a bunch of text files which contain a factual error and you urgently need to correct the same, then the obvious recourse would be to open each text file individually and search and replace the text. This process is very laborious and time consuming especially if the number of text files runs in 10s and 100s.
However, if you are a Linux or Apple Mac user, help is at hand. You can search for, and replace text across multiple files using a single command. Which means, you are able to do in a few seconds what would have normally taken you hours to accomplish.
Here is how it is done. Open a terminal in Linux/ Mac OS X and navigate to the directory in which you have your text files.
Now run the following command -
$ perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt
While running the above command, don’t forget to replace “SEARCH_FOR” string with the text you want to correct, and the “REPLACE_WITH” string with the text you want to substitute.
For example, if I want to replace the word oranges with apples in all the text files, I will run the above command as follows :
$ perl -pi -w -e 's/oranges/apples/g;' *.txt
It is a basic Perl command. However, ‘
grep syntax. The ‘
s‘ denote substitution; and ‘
g‘ denote global – meaning every occurrence of the word within the file.
[ Source : Lifehacker.com ]