Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I list top or bottom 10 lines from the line that matched the word 'error' in a file.

I'm using grep 'error' /var/log/logfile.log > errors to print and save the lines that matched the word 'error' in to the file called 'errors'. How could I change this to suite my requirement?. Anybody has any idea?

share|improve this question
up vote 3 down vote accepted

Displaying lines before/after/around the match using grep -A, -B and -C

-A is the option which prints the specified N lines after the match as shown below.

-B is the option which prints the specified N lines before the match.

-C is the option which prints the specified N lines before the match. In some occasion you might want the match to be appeared with the lines from both the side. This options shows N lines in both the side(before & after) of match.

Source: (Also I would recommend you to read the full blog post)

so, the command should be like grep -C 10 'error'

share|improve this answer
awesome!!!. It's really more than the one what I want and the link is really useful. Again a small thing, a file may have many lines matched the word and is it possible to differentiate/separate with some hashes or spaces or with something. – user3215 Mar 20 '11 at 14:54
Thanks! You can accept the answer as accepted. Regarding your question, are you trying to match selectively? I am not sure if that can be done by grep somehow without an example. I would suggest you to ask a different question explaining with an example so that others can help you out. – Ashfame Mar 20 '11 at 15:40
@user3215 if you want the first match or the last match, try piping through head or tail, respectively. Eg grep -C 10 'error'|head -n 10 – djeikyb Mar 20 '11 at 16:09
@djeikyb I think he actually wants to grep the "error" with a certain pattern around that word. – Ashfame Mar 20 '11 at 16:12
Eg: after the first 10 lines of from the line contains error, give some space/hashes and then print next 10 lines – user3215 Mar 21 '11 at 2:13

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.