如何显示字符串匹配前后的所有行,直到在shell中检测到空行

2ul0zpep  于 2022-11-04  发布在  Unix
关注(0)|答案(1)|浏览(203)

我需要一个帮助grep一个文件,其中有大量的数据。我有一个文件与下面的行:

random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

Some data to be here as well 
This file is use for some analysis
Analysis code is <01267>
This is line after analysis

我想只打印那些有字符串“分析代码”与值“01234”的行,并打印它之前和之后的所有行。我试图得到解决方案的一半,但需要完整的逻辑。

egrep -i "Analysis code" c.txt |
grep -i 01234 |
awk -F "<" '{print $2}' |
awk -F ">" '{print $1}' |
uniq > am.txt
while read line ; do
    echo $line
    awk "/$line/,/$^/" c.txt
done <am.txt

在这之后,我只从具有分析代码的行开始得到输出。
我想打印匹配字符串之前的所有行,直到空行出现在顶部:

random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis
watbbzwu

watbbzwu1#

最简单的方法是使用grep选项来打印匹配行之前和之后的行:

grep c.txt -e "Analysis code.*<01234>" -B2 -A1

如果你想打印一个由空行分隔的段落,可以使用多行模式或awk,如下所示:
awk -v RS='' '/Analysis code.*<01234>/' c.txt

相关问题