How to find first previous occurrence of string resulting from grep

Viewed 61

I am trying to find a string occurring before my grep result.

before = text1234
foo = 1234
bar = 1234
var = words
    
before = text2345
foo = 2345
bar = 2345
etc = 2345
var = words

I am using grep grep -n var * to get the results of var. But I am trying to find the first occurrence of before before the grepped line.

I have tried using the grep -B 10 option, but since the lines are variable it is not exactly what I want.

The ideal result would return:

   before = text1234
    before = text2345

I think there is some sed/awk magic that would help, but I am not sure what it could be based on my google-fu

5 Answers

One option using awk is to match before = at the start of the string and then store the line.

Then when you encounter var = at the start of the string, check if there is a stored value for before = and then print that value.

awk '
/^before =/ {b=$0; next}
/^var =/ && b {print b; b=""}
' file

Output

before = text1234
before = text2345

Another option using a field separator of = and checking the first field values:

awk -F" = " '
$0 == "" {b="";next}
$1 == "before" {b=$0; next}
$1 == "var" && b {print b; b=""}
' file

This sed one-liner should do the job:

sed -n '/^before =/h; /^var =/{x; p;}' file

Another awk approach that works with shown example data:

awk '/^before /,/^var /{if ($1 == "before") print}' file

before = text1234
before = text2345

Chaining grep is easy here, too:

grep -e before -e var file | grep -B1 var | grep -v var

A variation on the other answers using awk and grep:

awk '/var/' RS= file | grep before

The awk part "greps" in "records" that are separated by empty lines. The grep part "greps" for before in the records found by awk that contain var.

Note that this solution relies in the blocks you are searching to be separated by an empty line.

Related