Friday, November 14, 2008

Finding lines of text following a text match - awk

Suppose you need to display x lines following a search condition.
For example, display the first 5 lines of trace following an Exception in Tomcat log.

If you are using Solaris/ Linux/ *nix, one way of doing it is to "awk" it.
Get the first five lines after a Keyword named "Exception". Feel free to change the keyword as required.
BEGIN {flag = 0}
/Exception/
{print;
flag = 5;
next}
flag >= 1 {print;
flag--;
next}

Use awk or nawk(if you have a long line - awk has a limitation on line length)
Run it as follows:
nawk -f checkex.awk *
Redirect to a file as follows
nawk -f checkex.awk * > output.txt

No comments: