繁体   English   中英

比较两个文件的两列,如果在 unix 中匹配,则显示带有输入的第三列

[英]Compare two columns of two files and display the third column with input if it matching of not in unix

我想比较两个文件 file1.txt 和 file2.txt 的前两列,如果它们匹配写入另一个文件 output.txt 与 file1,file 2 的第三列以及是否匹配的详细信息。

文件1.txt

ab|2001|name1
cd|2000|name2
ef|2002|name3
gh|2003|name4

文件2.txt

xy|2001|name5
cd|2000|name6
ef|2002|name7
gh|2003|name8

输出.txt

name1 name5  does not match
name2 name6  matches
name3 name7  matches
name4 name8  matches

欢迎使用堆栈溢出,请您尝试关注并告诉我这是否对您有帮助。

awk -F"|" 'FNR==NR{a[$2]=$1;b[$2]=$3;next} ($2 in a) && ($1==a[$2]){print b[$2],$3,"matched properly.";next} {print b[$2],$3,"Does NOT matched."}' file1.txt file2.txt

编辑:在这里也添加一种非单衬形式的解决方案。

awk -F"|" '
FNR==NR{
   a[$2]=$1;
   b[$2]=$3;
   next
}
($2 in a) && ($1==a[$2]){
   print b[$2],$3,"matched properly.";
   next
}
{
   print b[$2],$3,"Does NOT matched."
}
' file1.txt file2.txt

说明:为上述代码添加说明。

awk -F"|" '                                 ##Starting awk program from here and setting field separator as | here.
FNR==NR{                                    ##Checking condition if FNR==NR which will be TRUE when file1.txt is being read.
   a[$2]=$1;                                ##Creating an array with named a whose index is $2 and value is $1.
   b[$2]=$3;                                ##Creating an array named b whose index is $2 and value is $3.
   next                                     ##next will skip all further statements from here.
}                                           ##Closing BLOCK for FNR==NR condition here.
($2 in a) && ($1==a[$2]){                   ##Checking condition if $2 is in array a AND first field is equal to value of array a value of index $2.
   print b[$2],$3,"matched properly.";      ##Printing array b value with index $2 and 3rd field with string value matched properly.
   next                                     ##next will skip all statements from here.
}                                           ##Closing BLOCK for above condition here.
{
   print b[$2],$3,"Does NOT matched."       ##Printing value of array b with index $2 and 3rd field with string Does NOT matched here.
}
' file1.txt file2.txt                       ##Mentioning Input_file names here.

你可以使用 paste 和 awk 来获得你想要的。

下面的解决方案假设 file1 和 file2 中的字段将始终由“|”分隔

paste -d "|" file1.txt file2.txt | awk -F "|" '{ if( $1 == $4 && $2 == $5 ){print $3, $6, "matches"} else {print $3, $6, "does not match"} }' > output.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM