Programmer's Cookbook

Recipes for the practical programmer

Saturday, February 11, 2006

 

Replace Text In Multiple Files With Perl

You can use Perl at the command line (or even a short script) to make text replacements in a list of files. The key is to use three of Perl's command line switches.


-i[extension] In place editing of files.
-e 'code block' Evaluates the specified code.
-p Loops over code for each argument, prints $_.



These three switches combined will open each file that is passed as an argument, execute your code for each line in the file, and replace the original file with the output of rhe code. The -i switch takes an optional extension which it will use to create backups of the original (recommended!).

Replace all occurences of "foo" with "bar"

perl -pi.bak -e 's/foo/bar/g' *



Fix all href attributes in all HTML files to use "http://www.foo.com" instead of "http://www.bar.com", recursively.

# broken into multiple lines for readability

perl -pi.bak
-e 's!(href=(["']))http://www.foo.com\2!$1http://www.bar.com!g'
`find . -name \*.html`



See perldoc perlrun for more information on Perl's command line switches.

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?