Grep (or maybe regex) check for pattern on lines before or after a match
grep, regex
Solution
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'
Problem
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. ```