awk Compare 2 files, print match and difference

独自空忆成欢 提交于 2019-12-29 09:36:30

问题


I need to comapre two files f1.txt and f2.txt and obtain matches, and non-matches, for this case I am looking to match first field on both files. 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

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 am able to obtain the matches but not the non match

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

Thanks


回答1:


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



回答2:


This was very useful . I have changed a bit to get data between 2 files and only have 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


来源:https://stackoverflow.com/questions/13116353/awk-compare-2-files-print-match-and-difference

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!