比较两个文件的两列,如果与unix中的不匹配,则显示第三列与输入 [英] Compare two columns of two files and display the third column with input if it matching of not in unix

查看:71
本文介绍了比较两个文件的两列,如果与unix中的不匹配,则显示第三列与输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to compare the first two columns of two files file1.txt and file2.txt and if they match to write to another file output.txt with the third column of both file1,file 2 along with details if it matches or not .

file1.txt

file1.txt

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

file2.txt

file2.txt

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

output.txt

output.txt

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

推荐答案

欢迎堆栈溢出,能否请您尝试关注一下,让我知道这是否对您有帮助.

Welcome to stack overflow, could you please try following and let me know if this helps you.

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

编辑:在此处也添加了一种非线性形式的解决方案.

Adding a non-one liner form of solution too here.

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

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

Explanation: Adding explanation for above code.

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.

这篇关于比较两个文件的两列,如果与unix中的不匹配,则显示第三列与输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆