Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

1 Answer 1

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

 
discard

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.