0

Replace Text in Files with Perl

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/155.179.124.75/132.201.69.79/g’ *

The above command replaces 155.179.124.75 with 132.201.69.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 “.”

jlim0930

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.