多个grep和分组输出

时间:2018-12-16 11:52:32

标签: bash awk sed grep

输入:

--------------- 1st block ----------------

info1:AAAAA

random info

random info

random info

info0:"one string"

random info

random info

[...]

info2:"2nd string"


info3:"3rd string"

random info

random info

info4:"4th string"

--------------- 2nd block ----------------

info1:BBBBB

random info

random info

random info

info0:"one string"

random info

random info

[...]

info2:"2nd string" 

info3:"3rd string"

random info

random info


info4:"4th string"

--------------- 3rd block ---------------- 

[...]

注意:如果info0是我搜索的模式,我想获取info0,info1,info2,info3,info4

我可以执行grep info0 -B 4(以获取info1),但是我不能执行-A x来获取其余信息(info2,3,4),因为行的数量在一个块与另一个块之间可以不同。

重要:

 -the output should be grouped by info0

-info0, info2,info3,info4 is always the same, but info1 is always unique (actually info1 is a MAC address). 

-the number of blocks is not limited (there can be 1, 2 , 3, 4,...blocks).

-subsidiary question: within the same command, do the same thing but with info0 carrying different string. For instance: 2 blocks with the same info0, then 3 blocks with another info0 and so on and so forth...

 - I put ----- #block----- in the input to facilitate lecture to the reader, but these lines do not exist in the actual input. 

想要的输出:

info0:"one string"

info1:AAAAA

info1:BBBBB 

info2:"2nd string"

info3:"3rd string"

info4:"4th string"

到目前为止我做了什么

output | grep info0 -B 4 -A 23 | grep '\(info1\|info0\|info1\|info2\|info3\|info4\)' >> /tmp/info0

23->估计一个块的最大行数

非常感谢你们!

1 个答案:

答案 0 :(得分:-1)

我找到了一个坚固但可行的解决方案。假设我搜索info0,输入为/ tmp / input:

echo info0;grep info0 -B5 /tmp/input | grep info1;awk '/info0/{flag=1} flag; /info4/{flag=0}' /tmp/input | grep '\(info2\|info3\)' | sort -u