Tips Linux Explorers   All Things Linux Forum   Great Linux Links   LinuxClues.com   Hometown   Email 



FIND AND REPLACE with SED



Let us start off simple:
Imagine you have a large file ( txt, php, html, anything ) and you want to replace all the words "ugly" with "beautiful" because you just met your old friend Sue again and she/he is coming over for a visit.


This is the command:

CODE
$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt


Well, that command speaks for itself "sed" edits "-i in place ( on the spot ) and replaces the word "ugly with "beautiful" in the file "/home/bruno/old-friends/sue.txt"


Now, here comes the real magic:
Imagine you have a whole lot of files in a directory ( all about Sue ) and you want the same command to do all those files in one go because she/he is standing right at the door . .
Remember the find command ? We will combine the two:

CODE
$ find /home/bruno/old-friends -type f -exec sed -i 's/ugly/beautiful/g' {} \;


Sure in combination with the find command you can do all kind of nice tricks, even if you don't remember where the files are located !


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

CODE
#!/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




For the lovers of perl I also found this one:

CODE
# perl -e "s/old_string/new_string/g;" -pi.save $(find DirectoryName -type f)

But it leaves "traces", e.g it backs up the old file with a .save extension . . . so is not really effective when Sue comes around ;-/



Bruno


-- Jan 4 2005 ( Revised Dec 10 2005 ) --


Tips Linux Explorers   All Things Linux Forum   Great Linux Links   LinuxClues.com   Hometown   Email