Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

UNIX Scripting FAQ

Tips and Tricks

How to return lines before and after a match found with grep? by Ghodmode
Posted: 15 Jan 06

There is more than one way to do this, but this is the method I prefer...


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.

  1. tail +# gives the end of a file starting at # lines from the beginning of the file.
  2. grep -n precedes it's output with the line number of the match and a colon.
  3. cut -ddelimiter -f# uses the colon as a delimiter and returns the first field.
  4. $((expr)) 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 man bc.  So, my sample subtracts 5 from the line number and that is used for the first argument to tail.
  5. The second occurrence of the filename is an argument to the tail command at the beginning of the line.
  6. Pipe (|) the whole mess through head, which defaults to 10 lines.
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 -n to head.

Back to UNIX Scripting FAQ Index
Back to UNIX Scripting Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close