用find+sed批量替换文件中的字符串

作者:网络医生 发布于:2012-4-23 11:43 Monday 分类:Linux技术

1、首先简单了解一下find和sed的使用方法

find <目录列表>  <检索方式>  [<执行动作>]

<目录列表>:即指检索路径

<检索方式>:

-type  <文件类型>

f指一般文件,d目录文件,l 符号连接

-mtime <数目>

+3表示3天以前的文件,3表示前面第3天的文件,-3表示3天以内的文件

<执行动作>:

-exec <命令>  {}  \;   执行<命令>,其中分号是必不可少的且{}两边有空格,其中{}表示检索出来的文件,系统会在发现{}的地方将检索出来的文件名称传递给该命令。

 

sed -i 's#abc#efg#g'  filename

-i 表示直接对文件进行编辑。该命令就是把filename中所有的efg字符串替换成abc字符串。开头的s和结尾g是固定用法,不可少。#是字符分隔符号,也可以使用/代替。

 

2、实际案例

1)把test.log中的num123全部替换成abc

[root@linux study]# cat test.log
 http://www.num123.org/index.html
 http://www.num123.org/1.html
 http://post.num123.org/index.html
 http://mp3.num123.org/index.html
 http://www.num123.org/3.html
 http://post.num123.org/2.html

[root@linux study]# sed -i 's#num123#abc#g' test.log
[root@linux study]# cat test.log
 http://www.abc.org/index.html
 http://www.abc.org/1.html
 http://post.abc.org/index.html
 http://mp3.abc.org/index.html
 http://www.abc.org/3.html
 http://post.abc.org/2.html

如果目录下有一大堆文件需要替换怎么办:

find /home/test -type f -exec sed -i 's#num123#abc#g' {} \ ;

2)去掉文件中网址前面的http://

[root@linux study]# cat test.log
 http://www.abc.org/index.html
 http://www.abc.org/1.html
 http://post.abc.org/index.html
 http://mp3.abc.org/index.html
 http://www.abc.org/3.html
 http://post.abc.org/2.html
[root@linux study]# sed -i 's#http://##g' test.log
[root@linux study]# cat test.log
 www.abc.org/index.html
 www.abc.org/1.html
 post.abc.org/index.html
 mp3.abc.org/index.html
 www.abc.org/3.html
 post.abc.org/2.html


 

标签: shell find sed 字符串替换

发表评论:

  • 3
  • 2
  • 4
  • 9
  • 7

Powered by emlog