我有一个类似的日志文件;
A
some lines
some lines
Z
A
some lines
some lines
IMPORTANT text
some lines
Z
A
some lines
more lines
some lines
Z
A
some lines
IMPORTANT text
more lines
some lines
Z我只需要A-Z之间的行,如果它有重要的字.因此,期望的输出是;
A
some lines
some lines
IMPORTANT text
some lines
Z
A
some lines
IMPORTANT text
more lines
some lines
ZA之间的行数是可变的.我尝试了太多的命令,比如:
grep 'IMPORTANT' -A 3 -B 3 x.log | sed -n '/^A$/,/^Z$/p'
grep 'IMPORTANT' -A 3 -B 3 x.log | grep -E '^Z$' -B 5 | grep -E '^A$' -A 5有些印刷不需要从另一组,其他印刷线没有起点或终点..。都失败了。
有办法用一个班轮吗?
发布于 2016-01-21 20:36:47
使用gnu-awk您可以这样做:
awk 'BEGIN{RS=ORS="\nZ\n"} /^A/ && /IMPORTANT/' file
A
some lines
some lines
IMPORTANT text
some lines
Z
A
some lines
IMPORTANT text
more lines
some lines
ZBEGIN{RS=ORS="\nZ\n"}将输入和输出记录分隔符设置为Z,两边都有换行符。/^A/ && /IMPORTANT/确保每个记录都以A开头,并在其中包含IMPORTANT。awk中的默认操作。发布于 2016-01-21 20:31:32
使用sed:
sed -n '/^A$/{:a;N;/\nZ$/!ba;/IMPORTANT/p}' x.log解释:
/^A$/ { # If line matches ^A$...
:a # Label to branch to
N # Append next line to pattern space
/\nZ$/!ba # Branch to :a if pattern space doesn't end with \nZ
/IMPORTANT/p # Print if pattern space contains IMPORTANT
}这基本上是附加行,直到我们在模式空间中有一个完整的块,然后如果它与IMPORTANT匹配,就打印它,否则就丢弃它。
当我们到达循环结束时,-n选项会阻止输出。
有些seds不支持带有命令分组({}和;)或内联注释的oneliners。对于某些seds,让p;而不是p工作,而对于另一些seds,这(基本上是上面的减注释)应该可以工作(并且符合POSIX ):
sed -n '/^A$/{
:a
N
/\nZ$/!ba
/IMPORTANT/p
}' x.loghttps://stackoverflow.com/questions/34933553
复制相似问题