【问题标题】:Compare two columns of two files and display the third column with input if it matching of not in unix比较两个文件的两列,如果在 unix 中不匹配,则将第三列显示为输入
【发布时间】:2019-12-07 12:44:15
【问题描述】:

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

file1.txt

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

file2.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吗?
  • 是的,但我无法打印出第一个文件的第三列
  • 那么请具体说明您的尝试。

标签: shell unix awk


【解决方案1】:

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

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.

【讨论】:

  • 你能解释一下这个答案的逻辑吗?
  • @Donbhupi,请几分钟后添加。
【解决方案2】:

你可以使用 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

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多