In this example, need to compare two files f1.txt and f2.txt and obtain matches, and non-matches, for this case I am looking to match 2nd field of second file and 1st field of first file. And print first the second field of f2.txt, then print the entire line of f1.txt. And for no match found on f2.txt to state "Not Found" and then print f1.txt entire 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
First;1
Firsta;1a
Firstb;1b
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;Not Found;2b;2;3;4;5;6;7;8
Tried but not working:
awk -F";" 'NR==FNR{a[$1]=$0;b[$1]=$0;next}{ if (a[$2]=b[$1]) print a[$1],$0;else print "NotAvailable","NotAvailable", $0;}' OFS=";" f2.txt f1.txt
You were close. Here is the correct script:
$ awk -F ";" 'NR==FNR{a[$2]=$0;next}{print (a[$1]?a[$1]:"Not Found;Not Found") ";" $0}' F2.txt F1.txt
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;Not Found;2b;2;3;4;5;6;7;8
Take care to remove any trailing spaces from the input file.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments