Regular expression to match error and associated few lines

I am looking for a single line regular expression to match the word "Error" from the log file and i need to get the few lines above and below the lines that has the word "Error" for debugging purpose.

For example: I need to match for the word " TypeError " and get other few lines above and below this matched lines. atleast i need next 10 lines. Could anyone please help on this ?

Log File content below =>

TypeError : Parameter 'url' must be a string, not undefined at Url.parse (url.js:107:11) at urlParse (url.js:101:5) at Object.urlResolve [as resolve] (url.js:404:10) at parseMarkdown (/opt/controllers/api/userguide.js:53:19) at /opt/controllers/api/userguide.js:33:17 at Object. (/opt/models/api.js:172:4) at /opt/lib/data/api.js:138:5 at IncomingMessage. (/opt/node_modules/httpunch/lib/_wrap_request.js:100:9) at IncomingMessage.g (events.js:180:16) at IncomingMessage.emit (events.js:117:20)


Try this (Fetches upto 10 preceding and succeeding lines)-

(?:(?:.*n){0,10}).*?Error.*(?:(?:n.*){0,10})

Demo

EDIT
Just read the comment about unix environment.
You can use Grep command using the same regex as above.
Like this -

$ grep -Pzo "(?:(?:.*n){0,10}).*?Error.*(?:(?:n.*){0,10})" <filename>

All credits to Kamehameha for this answer, it's based on his regexp, but I went ahead and made it a little bit simpler to follow with an accompanying explanation. It is not as perfect as the original though, but works pretty well.

Full expression

(n.*){0,10}(.*Error:.*)(n.*){0,10}

View on regexr

Match the error line itself

.*Error:.*

This line is actually quite simple. The only thing you need to know is that .* matches any number of characters (but not line breaks). So this line means "Find anything followed by "Error:" followed by anything"

Match any line

n.*

This is also pretty easy to understand: n (newline) followed by anything.

Match up to 10 lines

(n.*){0,10}

This takes the "full line" regex and applies it between 0 and 10 times, as many as possible (since regex is greedy by default).

Putting it all together

What we want is "10 lines + error line + 10 lines", so we just take what we made previously and put into one big statement.

(n.*){0,10}(.*Error:.*)(n.*){0,10}
链接地址: http://www.djcxy.com/p/19640.html

上一篇: 如何在搜索结果后添加一行?

下一篇: 正则表达式匹配错误和相关的几行