Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to return lines before and after a match found with grep?

Tips and Tricks

How to return lines before and after a match found with grep?

by  Ghodmode  Posted    (Edited  )
There is more than one way to do this, but this is the method I prefer...
Code:
tail +$((`grep -n "regex" file.log | cut -d: -f1` - 5)) file.log | head

This will give ten lines of a file, starting five lines before the matched expression.

[ol]
[li][tt]tail +#[/tt] gives the end of a file starting at # lines from the beginning of the file.[/li]
[li][tt]grep -n[/tt] precedes it's output with the line number of the match and a colon.[/li]
[li][tt]cut -ddelimiter -f#[/tt] uses the colon as a delimiter and returns the first field.[/li]
[li][tt]$((expr))[/tt] is a bashism that does some math for you. I think it works in Korn, too. If that one doesn't work for you, there are other ways to get the math done. Look at [tt]man bc[/tt]. So, my sample subtracts 5 from the line number and that is used for the first argument to [tt]tail[/tt].[/li]
[li]The second occurrence of the filename is an argument to the tail command at the beginning of the line.[/li]
[li]Pipe (|) the whole mess through [tt]head[/tt], which defaults to 10 lines.[/li]
[/ol]

So, you get 10 lines, starting at 5 lines before the match. If you want more, or different, lines, be sure to adjust both the 5 in the double-parentheses and add a [tt]-n[/tt] to [tt]head[/tt].
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top