您的位置:首页 > 运维架构 > Shell

shell脚本工具之sed命令

2015-03-23 14:06 573 查看
sed就是批处理的流编辑器,可以对来自文件或标准输入的输入流进行转换,sed通常被用作管道中的过滤器.由于sed仅仅对其输入进行一遍扫描,因此比其它交互式编辑器更加高效.

文件内容:
[root@tong1 opt]# cat sed.txt
1
tong
2
cheng
3
Hellow
4
Word
wu han
2 4 5
JD
Tao Bao
[root@tong1 opt]#

常用参数:
-n --只输出匹配的行
-e --多项编辑
-f --使用脚本对文件处理
-i --直接修改文件内容
-r --在脚本中使用扩展正则表达式

1.只显示匹配的行
[root@tong1 opt]# sed -n '2p' sed.txt
tong
[root@tong1 opt]# sed -n '/^J/,$p' sed.txt --以J开头到结尾输出
JD
Tao Bao
[root@tong1 opt]#

2.直接修改文件内容
[root@tong1 opt]# sed -i '/3/c 3.00' sed.txt
[root@tong1 opt]# grep '3.00' sed.txt
3.00
[root@tong1 opt]#

3.使用脚本名对文件处理
[root@tong1 opt]# cat 1.sh
#!/bin/sed -f
3,5p
[root@tong1 opt]# sed -n -f 1.sh sed.txt
2
cheng
3.00
[root@tong1 opt]#

4.对文件多项编辑
[root@tong1 opt]# sed -n -e '2p' -e '4p' sed.txt
tong
cheng
[root@tong1 opt]#

常用命令:
a --在匹配字符后新增
c --替换
d --删除
i --插入
p --打印.通常与参数 sed -n 一起用
s --取代.通常这个 s 的动作可以搭配正则表达式。例如 1,20s/old/new/g

5.在文件中追加内容
[root@tong1 opt]# sed '/2/a\1111111111' sed.txt
1
tong
2
1111111111
cheng
3.00
Hellow
4
Word
wu han
2
1111111111
JD
Tao Bao
[root@tong1 opt]#

6.替换匹配的内容
[root@tong1 opt]# sed '/2/c\1111111111' sed.txt
1
tong
1111111111
cheng
3.00
Hellow
4
Word
wu han
1111111111
JD
Tao Bao
[root@tong1 opt]#

7.删除文件的内容
[root@tong1 opt]# sed '3,10d' sed.txt
1
tong
JD
Tao Bao
[root@tong1 opt]#

8.打印文件中的内容
[root@tong1 opt]# sed -n '3,4p' sed.txt
2
cheng
[root@tong1 opt]# sed -n '/2/,5p' sed.txt
2
cheng
3.00
2
[root@tong1 opt]#

9.将匹配的内容保存到另一个文件中
[root@tong1 opt]# sed -n '3,4 w 2.txt' sed.txt
[root@tong1 opt]# cat 2.txt
2
cheng
[root@tong1 opt]#

本文出自 “一起走过的日子” 博客,请务必保留此出处http://tongcheng.blog.51cto.com/6214144/1623351
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: