Techy: Single Line Multiple File Search And Replace

May 12th, 2003 by Richy B. Leave a reply »

Whilst performing the server upgrades, Ensim Pro died and crashed the server forcing us to roll back to plain old Ensim on the Red Hat Linux box. After we had done that, we then had to restore all the customer data and I noticed a slight inconsistency in the data: for some reason, all the backup files had the wrong IP address stored in them! So after the backups were restored, I found the Apache virtual conf folder (/etc/httpd/conf/virtual) and executed the following command at the Linux shell prompt (as root):

/usr/bin/perl -pi -e ‘s/old_IP_address/new_IP_address/g’ *

This practically is a single line multiple file search and replace function and it works as follows:

  • usr/bin/perl start the Perl interpreter (the language this script is written in)
  • -p instruct perl to loop/repeat around the following instructions
  • i edit the specified files in place (i.e. alter the stated files)
  • -e “what follows is a single line command”
  • ‘s/old_IP_address/new_IP_address/g’ a Perl regular expression to subsitute the text old_IP_address with the text new_IP_address on a global basis (if you omit the ‘g’ it will only replace the first occurrence of the old_IP_address found in each file). Change to /gi for a global, case insensitive search if you require
  • * change files matching this wildcard (*=every file and extension: you could use “*.html” just to change files ending in .html if you wanted)

I hope this little script comes in handy to someone else, but I still wish that I hadn’t needed to work out how to do it 🙁

This post is over 6 months old.

This means that, despite my best intentions, it may no longer be accurate.

This blog holds over 12 years of archived content - during that time, I may have changed my opinion of something, technology will have advanced (and old "best standards" may no longer be the case), my technology "know how" has improved etc etc - it would probably take me a considerable amount of time to update all the archival entries: and defeat the point of keeping them anyway.

Please take these posts for what they are: a brief look into my past, my history, my journey and "caveat emptor".

2 comments

  1. Weyland says:

    Awesome!
    I was searching for a script that did this, thinking I’d have to learn how to
    modify it to fit my purposes, but this little “one-liner” does the trick superbly.

    Great job, and thanks for posting it!

    Best,

    Weyland

  2. Richy C. says:

    And if you are looking for a recursive version:

    find . -type f -exec /usr/bin/perl -pi -e ‘s/localhost/127.0.0.1/g’ {} \;

    Should help you out!

Leave a Reply

gamy-dance
%d bloggers like this: