Press "Enter" to skip to content

Techy: Single Line Multiple File Search And Replace

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 🙁

2 Comments

  1. Weyland Weyland

    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. 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

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.