Thursday, February 17, 2022

[SOLVED] How to find matches by multiple keys and extract values for matches on two consecutive lines?

Issue

I have a file with following lines

key1=value1 AND key2=value2 followed by some other text
key3 {value3} some text key4 - value4 and key5 - value5

Is it possible to extract the values 1,3, 4 and 5 and print ? Please note only consider matches where there are all the matches in two consecutive lines. If it makes it any easier I know the keys I'm looking for.

Output ( or something similar )

key1 = value1, key3=value3, key4 = value4, key5 = value5

Example 1 -

abc = 12ty3 AND jfk = 345 followed by some other text
klm {678er} some text plr - 567 and deg - 345

Output

abc = 12ty3, klm = 678er, plr = 567 , deg = 345

Example 2 -

xyz-232  abc = 126y3 AND jfk = 567 followed by some other text dre {567x}
klm {rtyyr} some text plr - 444 and deg - 555 some text 345 = uut

Output

abc = 126y3, klm = rtyyr, plr = 444, deg = 555 

Solution

Just match it with a proper regex.

For example GNU sed (for posixish sed just replace ex. \+ with \{1,\}) the following:

sed 'N;s/\([^ ]*[ ]\+\)\{0,1\}\([^ =]\+\)[ ]*=[ ]\{0,1\}\([^ ]\+\) [^ ]* \([^ =]\+\)[ ]*=[ ]*\([^ ]\+\)[^\n]*\n\([^ ]\+\) {\([^}]\+\)}.* [^ ]\+ - [^ ]\+ .* \([^ ]\+\) - \([^ ]\+\).*/\2 = \3, \4 = \5, \6 = \7, \8 = \9/' <<EOF
key1=value1 AND key2=value2 followed by some other text
key3 {value3} some text key4 - value4 and key5 - value5
abc = 12ty3 AND jfk = 345 followed by some other text
klm {678er} some text plr - 567 and deg - 345
xyz-232  abc = 126y3 AND jfk = 567 followed by some other text dre {567x}
klm {rtyyr} some text plr - 444 and deg - 555 some text 345 = uut
EOF

seems to work and generates the following output:

key1 = value1, key2 = value2, key3 = value3, key5 = value5
abc = 12ty3, jfk = 345, klm = 678er, deg = 345
abc = 126y3, jfk = 567, klm = rtyyr, deg = 555


Answered By - KamilCuk
Answer Checked By - Dawn Plyler (WPSolving Volunteer)