tags:

views:

462

answers:

2

I have a simple grep command that returns lines that match from a file. Here's the problem: Sometimes, when a line matches, I want to include the line before it. What I want is a way to find all the lines that match a pattern, then use a different pattern to see if the line before each of those results match.

Let's say I want to get all lines containing 'bar', and the line before each of those only if they contain 'foo'. Given an input like this:

    Spam spam eggs eggs
    Let's all go to the bar.
    Blah Blah Blah foo.
    Meh.
    foo foo foo
    Yippie, a bar.

I'd like a result like this:

    Let's all go to the bar
    foo foo foo
    Yippie, a bar.
+6  A: 

You can use the -B option to include context lines before the match (there's also -A for including context lines after, and -C for including context lines before and after). You can then pipe the result into another grep:

# Get all lines matching 'bar' and include one line of context before each match
# Then, keep only lines matching 'bar' or 'foo'
grep bar -B1 the-file | grep 'bar\|foo'
Adam Rosenfield
A: 

don't have to use grep 2 times

awk '/bar/ && p~/foo/{
  print p
  print  
  next
}/bar/{print}{ p=$0}' file
ghostdog74