linux 中输出匹配字符及其后的若干行

 

001、 sed实现

[root@PC1 test02]# ls
a.txt
[root@PC1 test02]# cat a.txt    ## 测试数据
01 02
05 06 x
09 10
44 66
33 77
13 14
17 18 k
21 22
88 99
25 26
21 22 x
25 26
22 33
44 66
77 44
[root@PC1 test02]# sed -n '/x$/,+2p' a.txt
05 06 x
09 10
44 66
21 22 x
25 26
22 33
[root@PC1 test02]# sed -n '/x$/,+2p' a.txt | sed '1~3d'     ## 输出匹配x之后的两行
09 10
44 66
25 26
22 33

 

002、awk实现

[root@PC1 test02]# ls
a.txt
[root@PC1 test02]# cat a.txt           ## 测试数据
01 02
05 06 x
09 10
44 66
33 77
13 14
17 18 k
21 22
88 99
25 26
21 22 x
25 26
22 33
44 66  
77 44                                       ## 输出匹配字符其后的两行
[root@PC1 test02]# awk '{if($0 ~ /x$/) {tmp = NR + 2; next}; if(NR <= tmp) {print $0}}' a.txt
09 10
44 66
25 26
22 33

 。

 

posted @ 2023-07-07 11:11  小鲨鱼2018  阅读(106)  评论(0编辑  收藏  举报