使用 awk/sed 打印与模式匹配的块中的文本

使用 awk/sed 打印与模式匹配的块中的文本

有如下文本,只需打印包含ABC:CDA*和 的块fgh:qwe

在 Awk 下尝试过,但它打印了所有数据。

awk -n  -v RS='' -v ORS='\n\n' 'match($0,".*fgh:qwe[^\n]*") { print substr($0,1,RLENGTH) }'

输入:

ABC:CDA_sd
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

axy:ABC_gf
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_ghg
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_jsagdh
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

输出:

ABC:CDA_sd
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_ghg
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_jsagdh
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

答案1

尝试:

awk -v RS= '/^ABC:CDA.*fgh:qwe$/{ print sep $0; sep=ORS }' infile

答案2

为了对输出格式有更多的控制,我建议Perl采用段落模式

perl -00nE 'say "$1" if /ABC:CDA(.*)fgh:qwe/s' example

Perl -00ne意思是:对于每个段落

答案3

在 GNU 中测试awk

awk '/^(axy:ABC_|ABC:CDA_)[[:lower:]]{2,6}$/ {check = ($1 == "axy:ABC_gf")} !check' file
ABC:CDA_sd
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_ghg
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

ABC:CDA_jsagdh
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

或者仅该数据:


awk '/^(axy:ABC_|ABC:CDA_)[[:lower:]]{2,6}$/ {check = ($1 == "axy:ABC_gf")} check' file
axy:ABC_gf
dfg:GFJ
dfg:jasdn
iop:yui
ghj:bhu
ghj:poi
fgh:qwe

相关内容