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;

2 Responses to “Replace text in multiple files with perl just in one line…”

  1. Ken says:

    Is it possible to use a replace-patterns.txt file to search replace expressions in a file?

  2. er.punit says:

    Hello Ken,

    You shoule be able to do it with the followign command like :

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

    Put all your lookfor and replace with pattern in file replace-patterns.txt.

    Thanks,
    Puneet

Leave a Reply