Searching Replacing Text with Sed

sed

We are starting text search and replace here.
Many times Linux Administrators have to deal with large files. Some times conditions are critical e.g We have thousands of files where we want to replace a specific string like techbabu.com into techbabu.net in general conditions it may become hard to replace text in large number of files.

This is the command:

sed -i 's/techbabu/techbabu2/g' /home/www/test.php

Well, that command speaks for itself “sed” edits “-i in place ( on the spot ) and replaces the word “techbabu with “techbabu2″ in the file “/home/www/test.php”

Now, Here is the real work:

Suppose we have a lot of files in a directory ( all about Logs ) and we want the same command to do all those files in one go.
Remember the find command ? We will combine the two:

Finally lets start it, and add it to start up.

find /home/www/logs -type f -exec sed -i 's/techbabu/techbabu2/g' {} \;

Also with find command you can do this trick.

Aditionally I did find a little script on the net for if you often have to find and replace multiple files at once:

#!/bin/bash
     for fl in *.php; do
     mv $fl $fl.old
     sed 's/FINDSTRING/REPLACESTRING/g' $fl.old > $fl
     rm -f $fl.old
     done

just replace the “*.php”, “FINDSTRING” and “REPLACESTRING” make it executable and you are set.

I changed a www address in 183 .html files in one go with this little script . . . but note that you have to use “escape-signs” ( \ ) if there are slashes in the text you want to replace, so as an example: ‘s/www.search.yahoo.com\/images/www.google.com\/linux/g’ to change www.search.yahoo.com/images to www.google.com/linux

One comment

  1. MarkSpizer says:

    great post as usual!

Leave a Reply

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

*