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!

UNIX: Find and replace text across multiple files []


    you can also get geeky and use regular expressions instead of straight up text, and be aware that certain characters will do stuff with the regexp (like []) which you'll need to escape if you use them.

    Handy. Is there a win7 equivalent? It would save me sooo much time to be able to specify a directory and include sub-directory's. I figure there must be a solution already out there but I can't find it.


      You should be able to download Perl for Windows and use pretty much the same command, I would think.

      Nice tip, by the way!

    Couldn't you just use SED? There is a version of sed for Windows also. Check this from :

    sed -i 's/foo/bar/g' – aka Stream Editor is a tool which should be in every sys admin’s toolkit. In this case every occurence of “foor” is replaced by “bar” in all the files found using the “find” command. Sed simply parses input and applies certain text transformations to it. There’s a lot to say about sed, you can find more at this tutorial ( - "Sed - An Introduction and Tutorial by Bruce Barnett")

Join the discussion!

Trending Stories Right Now