【问题标题】:join two files based on three columns基于三列连接两个文件
【发布时间】:2017-04-20 16:47:56
【问题描述】:

我有以下两个文件,我需要根据三列的值加入它们,如果不匹配,则在不匹配的列中打印 NA。

cat f1
AAA  0  node4  Activated  Unreachable  down
AAA  1  node3  Activated  Pingable     cool

cat f2 
AAA  0  node3  XYZ  Active

目前我得到的输出不正确:

 awk 'NR==FNR{a[$1]=$1;b[$2]=$2;c[$3]=$3;next} $1 in a && $2 in b &&  $3 in c{print $0}' f1 f2
AAA 0 node3 XYZ Active

期望的输出:

AAA 0 node4 Activated Unreachable down NA
AAA 1 node3 Activated Pingable    cool Active

【问题讨论】:

    标签: bash join awk


    【解决方案1】:

    awk 方法:

    awk 'NR==FNR{a[$1,$3]=$5; next}{$7="NA";if(($1,$3) in a){$7=a[$1,$3]} print}' f2 f1
    

    输出:

    AAA 0 node4 Activated Unreachable down NA
    AAA 1 node3 Activated Pingable cool Active
    

    a[$1,$3]=$5 - 使用第一个 $1 和第三个 $3 字段的组合作为数组键,将第五个字段 $5 的值存储在第二个文件 f2 中

    $7="NA"; - 使用默认值“NA”启动额外的第七个字段$7

    【讨论】:

      【解决方案2】:

      使用Awk 逻辑如下,

      awk 'FNR==NR{hash[$1FS$3]=$NF; next}{for(i in hash) if (match(i,$1FS$3)) { $(NF+1)=hash[i] } else { $(NF+1)="NA" } }1' f2 f1
      

      根据需要产生输出。

      AAA 0 node4 Activated Unreachable down NA
      AAA 1 node3 Activated Pingable cool Active
      

      想法是先解析第二个文件来存储状态,按节点值索引到数组hash中。然后在第一个文件上,对所有 indices 进行循环,如果 f1 上的 $3 中的值与散列值匹配,则相应地打印状态并且找不到它,只需打印 NA。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-12
        • 1970-01-01
        • 2021-05-17
        • 2018-07-15
        • 2021-10-26
        • 2013-09-29
        • 2012-10-11
        • 2015-12-20
        相关资源
        最近更新 更多