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

bash loop over two files and one file has two key values

This is file1:

line1
line2
line3
line4
line5

This is file2:

value: line1
id: 12
--
value: line3
id: 20
--
value: line10
id: 22
--
value: line14
id: 8

I want to do this:

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

compare the two files and if the second column of value in file2 doesn’t match the file1, then show the value line and id line

The expected output:

value: line10
id: 22
value: line14
id: 8

These are my failed attempts:

#!/usr/bin/bash

for all in "$(cat file1)"
do
    for ids in "$(cat file2 | grep value | awk {'print $2'})"
    do
        if [ "$all" != "$ids" ]
        then
            echo "$ids"
        fi
    done
done

>Solution :

With GNU awk. Elements of array f1 contain all rows of file1.

awk 'NR==FNR                     { f1[$0]=$0; next } 
     $1=="value:" && $NF!=f1[$NF]{ print; nr=NR }
     NR==nr+1                    { print } ' file1 file2

Output:

value: line10
id: 22
value: line14
id: 8

See: 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

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