Linux 中常用的sed命令

2019-09-23 09:03:16于丽

echo this is a test line | sed 's/w+/[&]/g'
[this] [is] [a] [test] [line]

所有以192.168.0.1开头的行都会被替换成它自已加localhost:

sed 's/^192.168.0.1/&localhost/' file
192.168.0.1localhost

子串匹配标记1

匹配给定样式的其中一部分:

echo this is digit 7 in a number | sed 's/digit ([0-9])/1/'
this is 7 in a number

命令中 digit 7,被替换成了 7。样式匹配到的子串是 7,(..) 用于匹配子串,对于匹配到的第一个子串就标记为 1,依此类推匹配到的第二个结果就是 2,例如:

echo aaa BBB | sed 's/([a-z]+) ([A-Z]+)/2 1/'
BBB aaa

love被标记为1,所有loveable会被替换成lovers,并打印出来:

sed -n 's/(love)able/1rs/p' file

组合多个表达式

sed '表达式' | sed '表达式'
等价于:
sed '表达式; 表达式'

引用

sed表达式可以使用单引号来引用,但是如果表达式内部包含变量字符串,就需要使用双引号。

test=hello
echo hello WORLD | sed "s/$test/HELLO"
HELLO WORLD

选定行的范围:,(逗号)

所有在模板test和check所确定的范围内的行都被打印:

sed -n '/test/,/check/p' file

打印从第5行开始到第一个包含以test开始的行之间的所有行:

sed -n '5,/^test/p' file

对于模板test和west之间的行,每行的末尾用字符串aaa bbb替换:

sed '/test/,/west/s/$/aaa bbb/' file

多点编辑:e命令

-e选项允许在同一行里执行多条命令:

sed -e '1,5d' -e 's/test/check/' file

上面sed表达式的第一条命令删除1至5行,第二条命令用check替换test。命令的执行顺序对结果有影响。如果两个命令都是替换命令,那么第一个替换命令将影响第二个替换命令的结果。

和 -e 等价的命令是 --expression:

sed --expression='s/test/check/' --expression='/love/d' file

从文件读入:r命令

file里的内容被读进来,显示在与test匹配的行后面,如果匹配多行,则file的内容将显示在所有匹配行的下面:

sed '/test/r file' filename

写入文件:w命令  

在example中所有包含test的行都被写入file里:

sed -n '/test/w file' example

追加(行下):a命令

将 this is a test line 追加到 以test 开头的行后面:

sed '/^test/athis is a test line' file

在 test.conf 文件第2行之后插入 this is a test line: