This question already has an answer here:

I know I can use -A, -B and -C to show surrounding lines but all of them also show the matching line. What I'm trying to make here is so, in this example file:


I'd be doing something like grep <option> "bar" file and my output should be

Side note: I know the way of doing it with another grep or using sed but I would like to do it just by using one time grep

marked as duplicate by don_crissti, Gert, Archemar, dr01, Anthon May 30 '16 at 11:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • what if your file has two consecutive lines with bar ? what should it return ? – PinkFloyd May 30 '16 at 8:22
  • @PinkFloyd it does not, is always like that as I prepare it before to be like so. – sysfiend May 30 '16 at 8:49

It's quite a job for sed:

$ printf 'foo\nbar\n' | sed -n '$!N;/\nbar$/P;D'
  • 1
    this is the only answer so far that actually answers the question that was asked. – cas May 30 '16 at 8:50

Another possible solution:

grep -B 1 "bar" test | sed '/bar/d'

yet another solution

grep -B 1 "bar" test | head -n 1

it has the advantage that you don't need any additional regexp or matching test, it is therefore more efficient but this won't work for multiple match


You could do another grep which ignores "bar":

grep -B 1 "bar" test.txt | grep -v "bar"

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