Tuesday, August 14, 2012

How to Quickly Find and Replace Text Across Multiple Files with One Command


If you need to find and replace the occurrence of a word, phrase, URL, or whatever, and it’s in several documents, this can be a really tedious task. If you’re running Mac OS X, Linux, or really any Unix-based operating system, you can use the command line to save you a lot of time and effort.

All you really need is this simple command:

perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt

The search string is what you need to alter. You want to replace SEARCH_FOR with the text you’re searching for and REPLACE_WITH with the text you want to use as a replacement. You’ll also want to change *.txt if you’re working with HTML files (or another type of text file). This command also assumes you’re in the directory you want, so you’ll also need to use cd to change to the directory you want or will have to specify the full path. For example:

perl -pi -w -e 's/stupid/awesome/g;' ~/Desktop/*.txt

The above command will replace all occurrences of “stupid” with “awesome” found in any .txt files on the desktop. Pretty neat!

No comments:

Post a Comment