sed
语法形式
sed [选项] '[模式][动作]' [参数]
选项
-n #取消内存空间默认输出;不添加时sed命令会默认输出文件所有内容,添加后只会输出过滤出的内容
-r #使模式中的正则表达式支持扩展正则
模式
number #按行查找,查找第n行
number/正则符号,number/正则符号 # 查找n到m行
/字符串或正则表达式/ # 模糊查询,查询包含此字符串的行
/开头字符串/,/结尾字符串/ # 匹配区间:查询两个字符串之间的内容(也可用正则)
动作
p #输出打印过滤出的内容
d #删除过滤出的内容
[number]c 字符串 #将第n行替换为xxx
[number]i 字符串 #在第n行插入xxx
[number]a 字符串 #在第n行追加xxx
s###g #1.其中,g代表全局替换
#2.s///g与s@@@g与s###g效果相同
示例
1.a.txt文件
[root@Dezyan ~]# cat -n a.txt
1 The first snow came.
2 How beautiful it was, falling so silently all day long,
3 all night long.
4 on the mountains, on the meadows,
5 on the roofs of the living, on the graves of the dead! A
2.查看a.txt文件第三行的内容
[root@Dezyan ~]# sed -n '3p' a.txt
all night long.
3.查看a.txt文件中第三行到结尾的内容
[root@Dezyan ~]# sed -n '3,$p' a.txt
all night long.
on the mountains, on the meadows,
on the roofs of the living, on the graves of the dead! A
4.查看a.txt中以o开头或以T开头的行
[root@Dezyan ~]# sed -rn '/^o|^T/p' a.txt
The first snow came.
on the mountains, on the meadows,
on the roofs of the living, on the graves of the dead! A
5.查看a.txt文件中包含so与meadows行之间的内容
[root@Dezyan ~]# sed -n '/so/,/meadows/p' a.txt
How beautiful it was, falling so silently all day long,
all night long.
on the mountains, on the meadows,
6.在a.txt文件1到3行后都添加一行Dezyan
[root@Dezyan ~]# sed '1,3i Dezyan' a.txt
Dezyan
The first snow came.
Dezyan
How beautiful it was, falling so silently all day long,
Dezyan
all night long.
on the mountains, on the meadows,
on the roofs of the living, on the graves of the dead! A
7.将a.txt文件中所有的(第一个)on替换为under
[root@Dezyan ~]# sed 's#on#under#g' a.txt (只替换第一个只需将g去掉即可)
The first snow came.
How beautiful it was, falling so silently all day lunderg,
all night lunderg.
under the mountains, under the meadows,
under the roofs of the living, under the graves of the dead! A
8.查找roofs所在行,并将其替换为floor,并且只显示替换行
[root@Dezyan ~]# sed -n '/roofs/s#roofs#floor#gp' a.txt
on the floor of the living, on the graves of the dead! A
注意:
- 动作中有p,选项中必有n
- 在使用匹配区间( /开头字符串/,/结尾字符串/ )时,尽量使用文件内容中唯一的、不重复的字符串;
- 若只有一个开头,有两个甚至多个结尾时:输出的内容只会是开头到第一个结尾字符串之间的内容;
- 若只有开头,结尾字符串没有:输出的内容为开头字符串到文件末尾;