Shell的sed命令

来源:互联网 发布:杭州app软件开发 编辑:程序博客网 时间:2024/04/28 18:56
一 作用
sed是一种几乎包括在所有UNIX平台(包括Linux)的轻量级流编辑器。sed主要是用来将数据进行选取、替换、删除、新增的命令。
 
二 语法
sed [选项] ‘[动作]’ 文件名
选项:
-n:一般sed命令会把所有数据都输出到屏幕,如果加入此选择,则只会把经过sed命令处理的行输出到屏幕。
-e:允许对输入数据应用多条sed命令编辑
-i:用sed的修改结果直接修改读取数据的文件,而不是由屏幕输出。
动作:
a:追加,在当前行后添加一行或多行
c:行替换,用c后面的字符串替换原始数据行。
i:插入,在当前行前插入一行或多行。
d:删除,删除指定行。
p;打印,输出指定的行
s:字符串替换,用一个字符串替换另外一个字符串。格式为“行范围s/旧字串/新字串/g”
 
三 实例
[root@localhost ~]# cat student.txt
ID Name sex score
1 furong F 85
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed '2p' student.txt
ID Name sex score
1 furong F 85
1 furong F 85
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed -n '2p' student.txt
1 furong F 85
 
[root@localhost ~]# sed '2d' student.txt
ID Name sex score
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed '2,4d' student.txt
ID Name sex score
[root@localhost ~]# sed '2a piaoliang' student.txt
ID Name sex score
1 furong F 85
piaoliang
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed '2i piaoliang' student.txt
ID Name sex score
piaoliang
1 furong F 85
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed '2c piaoliang' student.txt
ID Name sex score
piaoliang
2 fengj F 60
3 cang F 70
[root@localhost ~]# sed 's/70/100/g' student.txt
ID Name sex score
1 furong F 85
2 fengj F 60
3 cang F 100
[root@localhost ~]# sed -i 's/70/100/g' student.txt
[root@localhost ~]# cat student.txt
ID Name sex score
1 furong F 85
2 fengj F 60
3 cang F 100
[root@localhost ~]# sed -e 's/furong//g;s/fengj//g' student.txt
ID Name sex score
1 F 85
2 F 60
3 cang F 100
 
 
原创粉丝点击