Awk Compare 2 Files, Print Match and Difference

I need to link two files f1.txt and f2.txt and get matches and not matches for this case. I am looking for the match of the first field in both files. And first print the second field of the f2.txt file, then print the entire line of the f1.txt file. And no match was found on f2.txt to indicate "Not Found" and then print the entire f1.txt line.

F1.txt

1;2;3;4;5;6;7;8
1a;2;3;4;5;6;7;8
1b;2;3;4;5;6;7;8
2b;2;3;4;5;6;7;8

      

F2.txt

1;First
1a;Firsta
1b;Firstb

      

Desired output:

First;1;1;2;3;4;5;6;7;8
Firsta;1a;1a;2;3;4;5;6;7;8
Firstb;1b;1b;2;3;4;5;6;7;8
Not Found;2b;2;3;4;5;6;7;8

      

I can get matches, but not mismatches

awk -F ";" -v OFS="";"" "NR==FNR{a[$1]=$2;next}a[$1]{print a[$1],$0}" f2.txt f1.txt

      

thank

0


source to share


2 answers


This should do:



awk -F";" 'NR==FNR{a[$1]=$2;next}{if (a[$1])print a[$1],$0;else print "Not Found", $0;}' OFS=";" f2.txt f1.txt

      

+3


source


It was very helpful. I changed a bit to get data between 2 files and only 1 column in each file.



awk 'BEGIN { OFS=FS=";" } FNR==NR { array[$1]=$1; next } { print ($1 in array ? array[$1] : "Not Found"), $0 }' file1 file2

      

0


source







All Articles