sed命令

sed [选项] '[行地址][操作]' [文件]

选项:
-r:使用扩展的正则表达式
-n:屏蔽默认输出
-i:直接在文件中操作

行地址:
"行号"表示的行或者"/正则表达式/"匹配的行

操作:
a;增加一行
d:删除一行
c:替换一行
s:字符串替换

增加一行

//在第1行的下面添加一行
sed '1a helloworld' test.txt

//在第1行到第3行的下面分别添加一行
sed '1,3a helloworld' test.txt

//在包含hello的行下面添加一行
sed '/hello/a helloworld' test.txt

删除行

//删除第1行
sed '1d' test.txt

//删除第1行到第3行
sed '1,3d' test.txt

//删除第1行到最后一行
sed '1,$d' test.txt

//删除空行
sed '/^$/d' test.txt

//删除包含helloworld的行
sed '/helloworld/' test.txt

替换一行

//替换第1行
sed '1c helloworld' test.txt

//替换第1行到第3行
sed '1,3c helloworld' test.txt

//替换空行
sed '/^$/c space' test.txt

//替换包含hello的行
sed '/hello/c helloworld' test.txt

字符串替换

//将man全部替换为woman
sed 's/man/woman/g' test.txt
原文地址:https://www.cnblogs.com/smallredness/p/11093836.html