简体   繁体   English

用于检索日志文件中前一行的正则表达式

[英]A regular expression to retrieve the previous line in a log file

My log files contain the following: 我的日志文件包含以下内容:

 2009-03-12T12:44:27+0000 something was logged 2009-03-12T12:45:36+0000 127.0.0.1 127.0.0.1 <auth.info> last message repeated 2 times 

I can write a regular expression that retrieves the line with the "last message repeated..." statement, however, that line is meaningless without also retrieving the line that precedes it. 我可以编写一个正则表达式来检索带有“重复的最后一条消息...”语句的行,但是,该行是没有意义的,而又不检索其前面的行。

With that being said, does anyone know of a regular expression that would allow me to retrieve both lines whenever the "last message repeated..." statement is detected? 话虽如此,是否有人知道一个正则表达式,只要检测到“最后一条消息重复...”语句,我就可以同时检索这两行?

Edited to be 2 group matching regex. 编辑为2组匹配的正则表达式。 You can give it a shot at: RegexLib 您可以在以下地方一下: RegexLib

Less then optimized but this: 较少,然后优化,但这:

([\r\n].*?)(?:=?\r|\n)(.*?(?:last message repeated).*)

Should work to get results out of something like this: 应该可以从以下结果中获得结果:

2009-03-12T12:44:27+0000 something1 was logged
2009-03-12T12:44:27+0000 something2 was logged
2009-03-12T12:45:36+0000 127.0.0.1 127.0.0.1 <auth.info> last message repeated 2 times
2009-03-12T12:44:27+0000 something3 was logged
2009-03-12T12:44:27+0000 something4 was logged
2009-03-12T12:44:27+0000 something5 was logged
2009-03-12T12:45:36+0000 127.0.0.1 127.0.0.1 <auth.info> last message repeated 2 times

Resulting in: 导致:

Matches
First Match, First Group: 2009-03-12T12:44:27+0000 something2 was logged
First Match, Second Group: 2009-03-12T12:45:36+0000 127.0.0.1 127.0.0.1 <auth.info> last message repeated 2 times
Second Match, First Group: 2009-03-12T12:44:27+0000 something5 was logged 
Second Match, Second Group: 2009-03-12T12:45:36+0000 127.0.0.1 127.0.0.1 <auth.info> last message repeated 2 times

I would do it this way. 我会这样做。 Try to search for pattern that includes two groups. 尝试搜索包括两个组的模式。 First group is a line followed by another group containing another line with "last message repeated" text. 第一组是一行,其后是另一组,其中包含另一行带有“最后一条重复的消息”文本。 Then the content of the first group is the text you are looking for. 然后,第一组的内容就是您要查找的文本。

Something like this (this is overly simplified regex): 这样的事情(这是过于简化的正则表达式):

\n(.*)\n(.*)last message repeated

Now first group value contain the line you are interested in. 现在,第一个组值包含您感兴趣的行。

Does it have to be regex? 它必须是正则表达式吗? grep allows you to get a context before and after match ( -B NUM and -A NUM options) grep允许您在匹配之前和之后获取上下文( -B NUM-A NUM选项)

The pattern ^.*$ matches a whole line. 模式^。* $匹配整行。 Translation: Start Of Line, followed by any number of characters, followed by End Of Line. 翻译:行首,后跟任意数量的字符,后跟行尾。 So perhaps you can search for "any line, followed by" (the pattern you have there). 因此,也许您可​​以搜索“任意行,后跟”(那里的模式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM