Online Shopping : Computers : Programming : Languages : Perl

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

176 of 186 people (95%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

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?

Feb 2nd, 2005 09:12
matt wilkie, Shashank Tripathi,


Following is a handy little command to get the job done. Assuming you
are in the directory where you want to effect this search/replace --
perl -pi -e 's/lookFor/replaceWith/' *.fileExtension
perl -pi -e 's/lookFor/replaceWith/g' *.fileExtension
perl -pi -e 's/lookFor/replaceWith/gi' *.fileExtension
NOTES:
- 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
where replace-patterns.txt looks like (don't forget the semicolon!):
   s/lookForPatternOne/replaceWithOne/;
   s/lookForPatTwo/replaceWithTwo/g;
   s/lookForPatThree/replaceWithThree/gi;