[英]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. 在此示例中,需要比较两个文件f1.txt和f2.txt并获得匹配项和不匹配项,在这种情况下,我希望匹配第二个文件的第二列和第一个文件的第三列。 And print first the second field of f2.txt, then print the entire line of f1.txt. 并首先打印f2.txt的第二个字段,然后打印f1.txt的整行。 And for no match found on f2.txt to state "Not Found" and then print f1.txt entire line. 并且在f2.txt上找不到匹配项以声明“未找到”,然后打印f1.txt整行。
F1.txt 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 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
Basically it is taken from http://backreference.org/2010/02/10/idiomatic-awk/ . 基本上是从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"
. t=($3 in a)?a[$3]:"Not found"OFS"Not found"
。 It is a ternary operator var= check_condition ? value_if_true : value_otherwise
它是三元运算符var= check_condition ? value_if_true : value_otherwise
var= check_condition ? value_if_true : value_otherwise
. var= check_condition ? value_if_true : value_otherwise
。 So t
contains the line we need if the value is in the second file; 如果值在第二个文件中,则t
包含我们需要的行; otherwise, it contains the "Not found" value. 否则,它包含“未找到”值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.