-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

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

4 Answers 4

5

It's quite a job for sed:

$ printf 'foo\nbar\n' | sed -n '$!N;/\nbar$/P;D'
foo
5
  • 1
    this is the only answer so far that actually answers the question that was asked. Commented May 30, 2016 at 8:50
  • How does this work? Commented Oct 1, 2020 at 21:03
  • @theonlygusti What's part you don't understand? Commented Oct 2, 2020 at 3:33
  • @cuonglm '$!N;/\nbar$/P;D'. Commented Oct 2, 2020 at 3:49
  • @theonlygusti $!N -> If not last line, append next line to the pattern space. So If you are in line 1, your pattern space will look like line 1\nline2. Then /\nbar$/ will match if line 2 is bar. If yes, Print line 1, then Delete the rest of pattern space \nline 2. Commented Oct 2, 2020 at 8:10
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

0

Another possible solution:

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

You could do another grep which ignores "bar":

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.