使用 awk 在两个标记之间打印完整的文本块,仅当该块不包含特定关键字时

Print complete text block between two markers using awk, only if the block does not contain a specific keyword

我的文件中有一个特定的模式:

....
BEGIN
any text1
any text2
END
....
BEGIN
any text3
garbage text
any text4
END
....
BEGIN
any text5
any text6
END
...

BEGINEND 是我的标记,我只想在块不包含 'garbage text' 时提取标记之间的所有文本。所以我的期望是提取打击块:

any text1
any text2

any text5
any text6

如何在 awk 中执行此操作?我知道我可以做类似的事情:

awk '/BEGIN/{f=1;next}/END/{f=0;}f' file.log

提取两个标记之间的线,但如何根据缺少“garbage text”进一步过滤来进一步优化结果?

$ awk '/END/{if (rec !~ /garbage text/) print rec} {rec=rec [=10=] ORS} /BEGIN/{rec=""}' file
any text1
any text2

any text5
any text6

以上假定每个 END 都与前面的 BEGIN 配对。使用用于多字符 RS 的 GNU awk,您也可以这样做:

$ awk -v RS='END\n' '{sub(/.*BEGIN\n/,"")} RT!="" && !/garbage text/' file
any text1
any text2

any text5
any text6

顺便说一句,而不是:

awk '/BEGIN/{f=1;next}/END/{f=0;}f' file.log

您的原始代码应该是:

awk '/END/{f=0} f; /BEGIN/{f=1}' file.log

相关习语见。