Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading