Lofland bLOG

Replace Text in Files with Perl

Filed under Unix Notes on Monday, October 30th, 2006 @ 11:58am by Christen

I didn’t write this, just posting it here for my reference:

Subject: UNIX Trick

Here’s a really quick way to edit a bunch of files in a search and replace manner. For example, I had 80 files for sending test transactions and had to change the IP Addr when I copied them to each server. I could have manually edited each one, but by using the following, I was able to change it in all 80 in a matter of about 10 seconds. It’s done using “perl” from the command line and is similar to using global replaces within “vi” if you’ve ever used that.

perl -pi -e ’s/wordToFind/replaceWithThisWord/’ *.fileExtension
perl -pi -e ’s/wordToFind/replaceWithThisWord/g’*.fileExtension
perl -pi -e ’s/wordToFind/replaceWithThisWord/gi’*.fileExtension

Remember to escape any special characters like “*”, “.”, etc by putting a “\” in front. Here’s the command I used this morning that shows what I mean:

perl -pi -e ’s/192\.168\.1\.75/10\.0\.0\.79/g’ *

The above command replaces 192.168.1.75 with 10.0.0.79 in all the files in the directory I was working in. I put the “\” in front of the “.” to instruct perl to ignore the special meaning of the “.”

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress