当前位置: 动力学知识库 > 问答 > 编程问答 >

unix - awk compare 2 files, print match and nonmatch lines;3rd column of first file and 2nd column of second file

问题描述:

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 column of second file and 3rd column 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

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

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

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

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

F2.txt

First;1

Firsta;1a

Firstb;1b

Desired Output:

First;1;2;3;1;4;5;6;7;8

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

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

Not Found;Not Found;2;3;2b;4;5;6;7;8

网友答案:

This can be a way:

awk 'BEGIN{FS=OFS=";"}
     FNR==NR {a[$2]=$0; next}
     { t=($3 in a)?a[$3]:"Not found"OFS"Not found"; print t,$0}' f2 f1

It returns:

$ awk 'BEGIN{FS=OFS=";"}FNR==NR {a[$2]=$0; next} { t=($3 in a)?a[$3]:"Not found"OFS"Not found"; print t,$0}' f2 f1
First;1;2;3;1;4;5;6;7;8
Firsta;1a;2;3;1a;4;5;6;7;8
Firstb;1b;2;3;1b;4;5;6;7;8
Not found;Not found;2;3;2b;4;5;6;7;8

Explanation

Basically it is taken from http://backreference.org/2010/02/10/idiomatic-awk/ . The only aspect to explain should be:

  • t=($3 in a)?a[$3]:"Not found"OFS"Not found". It is a ternary operator var= check_condition ? value_if_true : value_otherwise. So t contains the line we need if the value is in the second file; otherwise, it contains the "Not found" value.
分享给朋友:
您可能感兴趣的文章:
随机阅读: