sed [-nefri] 'command' test.txt
sed |
|
|
command |
|
sed |
-e |
可以指定多个命令 |
a |
新增 |
|
-f |
指定命令文件 |
c |
整行替换 |
|
-n |
取消默认控制台输出,与p一起使用可打印指定内容 |
d |
删除 |
|
-i |
输出到原文件,静默执行(修改原文件的意思) |
i |
插入 |
|
|
|
p |
打印,要和-n参数一起使用 |
|
|
|
s |
替换(匹配局部替换) |
若不指定行号,则每一行都操作;$
代表最后一行,双引号"command"
内的$
代表使用变量,单引号'command'
内不能使用变量
新增 |
|
sed '2a testContent' test.txt |
在第 2 行后面新增一行内容 |
sed '1,3a testContent' test.txt |
在原文的第 1~3 行后面各新增一行内容 |
整行替换 |
|
sed '2c testContent' test.txt |
将第 2 行内容整行替换 |
sed '1,3c testContent' test.txt |
将第 1~3 行内容替换成一行指定内容 |
删除 |
|
sed '2d' test.txt |
删除第 2 行 |
sed '1,3d' test.txt |
删除第1~3行 |
sed –i “/$match/!d”
sed –i '/match/!d' |
删除(!=不)匹配的变量$match的行 注意双引号表示可以使用变量,不使用变量时需要使用单引号 |
插入 |
|
sed '2i testContent' test.txt |
在第 2 行前面插入一行内容 |
sed '1,3i testContent' test.txt |
在原文的第 1~3 行前面各插入一行内容 |
打印 |
|
sed '2p' test.txt |
重复打印第 2 行 |
sed '1,3p' test.txt |
重复打印第1~3行 |
sed -n '2p' test.txt |
只打印第 2 行 |
sed -n '1,3p' test.txt |
只打印第 1~3 行 |
sed -n '/user/p' test.txt |
打印匹配到user的行,类似grep |
sed -n '/user/!p' test.txt |
! 反选,打印没有匹配到user的行 |
sed -n 's/old/new/gp' test |
只打印匹配替换的行 |
替换 |
|
sed 's/old/new/' test.txt |
匹配每一行的第一个old替换为new |
sed 's/old/new/gi' test.txt |
匹配所有old替换为new,g 代表一行多个,i 代表匹配忽略大小写 |
sed '3,9s/old/new/gi' test.txt |
匹配第 3~9 行所有old替换为new |
多命令 |
|
sed -e 's/系统/00/g' -e '2d' test.txt |
执行多个指令 |
sed -f ab.log test.txt |
多个命令写进ab.log文件里,一行一条命令,效果同-e |