美文网首页
Linux OS sed命令使用

Linux OS sed命令使用

作者: 小米羊爱学术 | 来源:发表于2019-04-01 17:04 被阅读0次
命令 功能
a\ 在当前行后添加一行或多行。多行时除最后一行外,每行末尾需用“\”续行
c\ 用此符号后的新文本替换当前行中的文本。多行时除最后一行外,每行末尾需用""续行
i\ 在当前行之前插入文本。多行时除最后一行外,每行末尾需用""续行
d 删除行
h 把模式空间里的内容复制到暂存缓冲区
H 把模式空间里的内容追加到暂存缓冲区
g 把暂存缓冲区里的内容复制到模式空间,覆盖原有的内容
G 把暂存缓冲区的内容追加到模式空间里,追加在原有内容的后面
l 列出非打印字符
p 打印行
n 读入下一输入行,并从下一条命令而不是第一条命令开始对其的处理
q 结束或退出sed
r 从文件中读取输入行
! 对所选行以外的所有行应用命令
s 用一个字符串替换另一个
g 在行内进行全局替换
w 将所选的行写入文件
x 交换暂存缓冲区与模式空间的内容
y 将字符替换为另一字符(不能对正则表达式使用y命令)
[yangyang@izuf6btm1dq2w64mt5q889z practice]$ cat log.txt
2 this is a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

增加a
在第二行后增加新行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2a happy' log.txt
2 this is a test
3 Are you like awk
happy
This's a test
10 There are orange,apple,mongo

在第二行后增加多行 \n换行符

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2a happy\nchinese\nnew\nyear' log.txt
2 this is a test
3 Are you like awk
happy
chinese
new
year
This's a test
10 There are orange,apple,mongo

删除d
删除第二行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2d' log.txt
2 this is a test
This's a test
10 There are orange,apple,mongo

删除1-3行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '1,3d' log.txt
10 There are orange,apple,mongo

删除第二行后的所有行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2,$d' log.txt
2 this is a test

插入i
在第二行插入

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2i love' log.txt
2 this is a test
love
3 Are you like awk
This's a test
10 There are orange,apple,mongo

替换c
将第二行替换掉

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2c lololololo' log.txt
2 this is a test
lololololo
This's a test
10 There are orange,apple,mongo

将2-4行替换掉

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '2,4c lololololo' log.txt
2 this is a test
lololololo

输出p
输出第三行
-n是仅显示script处理后的结果,常和p一起连用

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed -n '3p' log.txt
This's a test

输出第1-3行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed -n '1,3p' log.txt
2 this is a test
3 Are you like awk
This's a test

搜寻
搜寻并输出包含“is”的行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed -n '/is/p' log.txt
2 this is a test
This's a test

搜寻并删除包含“is”的行

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed '/is/d' log.txt
3 Are you like awk
10 There are orange,apple,mongo

搜索并替换is为was(单词精确替换加<>)

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed 's/is/was/g' log.txt
2 thwas was a test
3 Are you like awk
Thwas's a test
10 There are orange,apple,mongo
[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed 's/\<is\>/was/g' log.txt
2 this was a test
3 Are you like awk
This's a test
10 There are orange,apple,mongo

多点编辑 -e
删除3-4行,然后将test替换为practice

[yangyang@izuf6btm1dq2w64mt5q889z practice]$ sed -e '3,4d' -e 's/test/practice/g' log.txt
2 this is a practice
3 Are you like awk

相关文章

网友评论

      本文标题:Linux OS sed命令使用

      本文链接:https://www.haomeiwen.com/subject/mkpvbqtx.html