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:

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

Leave a Reply