How to find first previous occurrence of string resulting from grep

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

>Solution :

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" = " '
$1 == "before" {b=$0; next}
$1 == "var" && b {print b; b=""}
' file

Leave a Reply