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

I'm fairly new to bash programming, and I am trying to figure out a way of "grepping" a line with a certain pattern from a rather long logfile and proceeding from the line I just got with grep -w "pattern" filename. I need to get to the line immediately preceding my grep-line.

I thought I could access it via linenumbers, but I only ever seem to find solutions that read a certain line via linenumber, if I already know, what that linenumber is.

Any ideas?

share|improve this question

You can tell grep to output additional lines of context around each matching line e.g.

grep -w "pattern" -A5 filename

for 5 lines of context after the match, or

grep -w "pattern" -B5 filename

for 5 lines of context before the match, or

grep -w "pattern" -C5 filename

for 5 lines each of before and after context. So in your case you could do

grep -w "pattern" -B1 filename | head -1

to find "pattern" and print a single preceding line of context, and then only print the context line using head. Other solutions using awk or sed instead of grep would be possible.

share|improve this answer

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.