sed 命令简介
命令模式
sed ‘ patternStart,patternEnd command’ files
基础命令-增删改查
- insert 命令例子
[root@shop988 zxl]# cat a.log
one
[root@shop988 zxl]# sed '1 i insert before first line' a.log
insert before first line
one
[root@shop988 zxl]#
- append 命令
[root@shop988 zxl]# cat a.log
one
[root@shop988 zxl]# sed '1 a append after first line' a.log
one
append after first line
[root@shop988 zxl]#
- delete 命令
[root@shop988 zxl]# cat a.log
one
two
[root@shop988 zxl]# sed '1 d' a.log
two
[root@shop988 zxl]#
- change 命令
[root@shop988 zxl]# cat a.log
one
two
[root@shop988 zxl]# sed '1 c change the first line' a.log
change the first line
two
[root@shop988 zxl]#
- swap 替换命令
[root@shop988 zxl]# cat a.log
one
two
[root@shop988 zxl]# sed '1 s/o/O/' a.log
One
two
[root@shop988 zxl]#
如何执行多个命令
将命令使用分号隔开即可执行多个命令
[root@shop988 zxl]# cat a.log
one
two
[root@shop988 zxl]# sed '1 s/o/O/; 2 s/t/T/;' a.log
One
Two
[root@shop988 zxl]#
如何指定一个复杂的模式区间
使用 {} 来组合模式
[root@shop988 zxl]# cat a.log
#one
one
#two
two
[root@shop988 zxl]# sed '{/#/{/e/ s/o/O/}}' a.log
#One
one
#two
two
如何使用N命令
N 命令代表合并两行, n命令代表不打印模式匹配行
[root@shop988 zxl]# cat a.log
#one
one
#two
two
[root@shop988 zxl]# sed 'N' a.log
#one
one
#two
two
[root@shop988 zxl]# sed 'N;s/\n//' a.log
#oneone
#twotwo
[root@shop988 zxl]#
[root@shop988 zxl]# cat a.log
#one
one
#two
two
[root@shop988 zxl]# sed -n '1,2 p' a.log
#one
one
[root@shop988 zxl]#
如何使用缓冲区命令
命令 | 解释 |
---|---|
g | 将缓存区内容覆盖到模式匹配区 |
G | 将缓存区内容追加到模式匹配区 追加时前置 \n |
h | 将模式匹配区内容覆盖到hold区 |
H | 将模式匹配区内容追加到hold区 追加时前置 \n |
x | 交互两个分区的内容 |
sed 为流式处理文件,有时需要把某些匹配的行放到hold区中,等触发某些条件时,再附加到模式匹配区打印出来。
[root@shop988 zxl]# cat a.log
#one
one
#two
two
[root@shop988 zxl]# sed -i '/^#/ d' a.log
[root@shop988 zxl]# cat a.log
one
two
[root@shop988 zxl]# sed 'H;$G;' a.log
one
two
one
two
[root@shop988 zxl]#
上面的例子展示了,将每行都缓存到hold区,在最后一行时将hold区内容追加到模式匹配区,然后一起打印出来。$G 代表最后一行执行G命令。
[root@shop988 zxl]# cat a.log
one
two
three
[root@shop988 zxl]# sed '1!G;h;$!d;' a.log
three
two
one
[root@shop988 zxl]#
上面的例子实现了文本倒转的功能, 1!G
代表除了一行外,都执行G命令。$!d
代表除了最后一行,都执行d命令。

This work is licensed under a CC A-S 4.0 International License.