Replace text in multiple files with perl just in one line…

How do I do a mass search and replace in a directory?

How can I search for a string in all my files and replace it with a text?

Are there any spiffy shortcuts for search/replace in a directory using command line Perl?

How do I load a list of replace patterns from a file in a one-liner?

Use this my all time favorite one line scripts ….:)

Assuming you are in the directory where you want to effect this search and replace

perl -pi -e ’s/lookFor/replaceWith/’ *.fileExtension

perl -pi -e ’s/lookFor/replaceWith/g’ *.fileExtension

perl -pi -e ’s/lookFor/replaceWith/gi’ *.fileExtension

Explanation :

- lookFor is the word you wish to look for.

- replaceWith is the word you wish to replace your original word with

- g stands for global, it will basically replace all the occurences of lookFor with replaceWith in all your files in a directory

- i stands for case insensitive

To load a series of replace expressions from a text file:

perl -pi -e "`/path/to/replace-patterns.txt`" *.fileExtension

s/lookForPatternOne/replaceWithOne/;

s/lookForPatTwo/replaceWithTwo/g;

s/lookForPatThree/replaceWithThree/gi;

Leave a Comment

"Quote of the Day"