问题描述
我已经学会了如何在匹配之前和之后grep
行以及如何grep
最后一个匹配,但我还没有发现如何grep代码>最后一个匹配项和它下面的行.
I've learnt how to grep
lines before and after the match and to grep
the last match but I haven't discovered how to grep
the last match and the lines underneath it.
场景是服务器日志.我想列出命令的动态输出.该命令很可能在一个服务器日志中多次使用.所以我想匹配将是命令,并且以某种方式 grep
可以将 -A
与一些其他标志或尾部命令的变体一起使用,以完成我正在寻求的结果.
The scenario is a server log.I want to list a dynamic output from a command. The command is likely to be used several times in one server log. So I imagine the match would be the command and somehow grep
can use -A
with some other flag or variation of a tail command, to complete the outcome I'm seeking.
推荐答案
我用来解决问题的方法,因为它更容易找到第一个匹配项并打印上下文行.取文件:
The approach I would take it to reverse the problem as it's easier to find the first match and print the context lines. Take the file:
$ cat file
foo
1
2
foo
3
4
foo
5
6
假设我们想要 foo
的最后一个匹配项以及接下来的 lines
我们可以使用 tac
反转文件,找到第一个匹配项和 n
行以上使用 -Bn
并停止使用 -m1
.然后用 tac 简单地重新反转输出:
Say we want the last match of foo
and the following to lines
we could just reverse the file with tac
, find the first match and n
lines above using -Bn
and stop using -m1
. Then simple re-reverse the output with tac:
$ tac file | grep foo -B2 -m1 | tac
foo
5
6
诸如tac
和rev
之类的工具可以使看似困难的问题变得更容易.
Tools like tac
and rev
can make problems that seem difficult much easier.
这篇关于grep 最后一场比赛,它是以下几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!