Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1365053
  • 博文数量: 416
  • 博客积分: 10495
  • 博客等级: 上将
  • 技术积分: 4258
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-23 22:13
文章分类

全部博文(416)

文章存档

2015年(7)

2014年(42)

2013年(35)

2012年(14)

2011年(17)

2010年(10)

2009年(18)

2008年(127)

2007年(72)

2006年(23)

2005年(51)

分类:

2009-02-24 19:04:08

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 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 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/\/images/\/linux/g' to change /images to /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 ;-/
阅读(2007) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~