-1

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:

foo
bar

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

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

sysfiend
  • 143

4 Answers4

5

It's quite a job for sed:

$ printf 'foo\nbar\n' | sed -n '$!N;/\nbar$/P;D'
foo
cuonglm
  • 153,898
3

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

PinkFloyd
  • 429
0

You could do another grep which ignores "bar":

grep -B 1 "bar" test.txt | grep -v "bar"
agold
  • 533
  • 5
  • 12
0

Another possible solution:

grep -B 1 "bar" test | sed '/bar/d'
phk
  • 5,953
  • 7
  • 42
  • 71