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 ;-/


출처 : http://www.nicegass.co.kr/52

'개발 > Linux' 카테고리의 다른 글

[LINUX] Subversion설치  (0) 2011.02.07
[LINUX] CentOS 5.5에 CMake 설치  (0) 2010.12.20
[LINUX] NFS 설치 및 설정  (0) 2010.11.11
[LINUX] HDD 복사  (0) 2010.10.28
[LINUX] TIME SYNC  (0) 2010.10.28
Posted by 나랑살자
,