linux 中awk命令实现输出匹配字符的上下若干行

发布时间 2023-06-03 20:22:55作者: 小鲨鱼2018

 

001、

[root@PC1 test3]# ls
test.txt
[root@PC1 test3]# cat test.txt           ## 测试数据
jjjj    kkk
gene    jjj
dddd    yyy
iiii    ppp
ffff    999
gene    ttt
eeee    mmm
aaaa    nnn
[root@PC1 test3]# awk 'BEGIN{idx = 0} {ay1[NR] = $0; if($1 == "gene") {idx++; ay2[idx] = NR}} END {for (i in ay2)  {print ay1[ay2[i]]; print ay1[ay2[i]+1]}}' test.txt
gene    jjj
dddd    yyy
gene    ttt
eeee    mmm
[root@PC1 test3]# awk 'BEGIN{idx = 0} {ay1[NR] = $0; if($1 == "gene") {idx++; ay2[idx] = NR}} END {for (i in ay2)  {print ay1[ay2[i]-1]; print ay1[ay2[i]]}}' test.txt
jjjj    kkk
gene    jjj
ffff    999
gene    ttt