sed高级指令

N命令

n命令

n命令简单来说就是提前读取下一行,覆盖模型空间前一行,然后执行后续命令。然后再读取新行,对新读取的内容重头执行sed

//从test文件中取出偶数行
[root@localhost ~]# cat test
This is 1   
This is 2   
This is 3   
This is 4   
This is 5
[root@localhost ~]# sed –n ‘n;p’ test
This is 2   
This is 4   

N命令

N命令简单来说就是追加下一行到模式空间,同时将两行看做一行,但是两行之间依然含有\n换行符,然后执行后续命令。然后再读取新行,对新读取的内容重头执行sed。此时,新读取的行会覆盖之前的行(之前的两行已经合并为一行)

//从test文件中读取奇数行
[root@localhost ~]# cat test
This is 1   
This is 2   
This is 3   
This is 4   
This is 5
[root@localhost ~]# sed –n 'N;P' test //因为读取第5行时,执行N,发现没有第6行,不满足,就退出,放弃P命令
This is 1   
This is 3   
[root@localhost ~]# sed –n '$!N;P' test   
This is 1   
This is 3   
This is 5

读取1,$!条件满足(不是尾行),执行N命令,得出1\n2,执行P,打印得1,读取3,$!条件满足(不是尾行),执行N命令,得出3\n4,执行P,打印得3,读取5,$!条件不满足,跳过N,执行P,打印得5

D命令

d命令

d命令是删除当前模式空间内容(不再传至标准输出),并放弃之后的命令,并对新读取的内容,重头执行sed

[root@localhostl ~]# cat test
This is 1   
This is 2   
This is 3   
This is 4   
This is 5 
[root@localhostl ~]# sed  'n;d'  test
This is 1   
This is 3   
This is 5

D命令

D命令是删除当前模式空间开端至\n的内容(不在传至标准输出),放弃之后的命令,但是对剩余模式空间重新执行sed

[root@localhostl ~]# cat test
This is 1   
This is 2   
This is 3   
This is 4   
This is 5 

[root@localhostl ~]#sed  'N;D'  aaa           
This is 5 

P命令

同 d 和 D 之间的区别一样,P(大写)命令和单行打印命令 p(小写)不同,对于具有多行数据的缓冲区来说,它只会打印缓冲区中的第一行,也就是首个换行符之前的所有内容

[root@localhostl ~]# cat test
This is 1   
This is 2   
This is 3   
This is 4   
This is 5 

[root@localhostl ~]# sed -n 'N;p' test
This is 1
This is 3

[root@localhostl ~]# sed -n 'N;P' test
This is 1
This is 2
This is 3
This is 4
命令 功能
h 是将当前模式空间中内容覆盖至缓存区
H 是将当前模式空间中的内容追加至缓存区
g 命令是将当前缓存区中内容覆盖至模式空间
G 是将当前缓存区中的内容追加至模式空间
x 是将当前缓存区和模式空间内容互换
[root@localhostl ~]# cat test2
1
2
11
22
111
222

[root@localhostl ~]# sed '
> /1/{
> h      
> d
> }
> /2/{
> G
> }' test2
2
1
22
11
222
111

x命令

[root@localhostl ~]# cat test3
hello world
hello runtime

hehe
xixi

henhen
haha

end

[root@localhostl ~]# sed '
> /^$/!{
> H
> d
> }
> /^$/{
> x
> s/^\n/<p>/
> s/$/<\/p>/
> G
> }' test3

<p>hello world
hello runtime</p>

<p>hehe
xixi</p>

<p>henhen
haha</p>
posted @ 2021-03-29 22:55  吻如雪上霜  阅读(75)  评论(0编辑  收藏  举报