Home > Mobile >  How to find first previous occurrence of string resulting from grep
How to find first previous occurrence of string resulting from grep

Time:09-08

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

CodePudding user response:

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

CodePudding user response:

This sed one-liner should do the job:

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

CodePudding user response:

Chaining grep is easy here, too:

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

  • Related