【问题标题】:AWK - Compare files, Match in Fields in specific order, X number of fields to checkAWK - 比较文件,按特定顺序匹配字段,要检查 X 个字段
【发布时间】:2018-04-17 03:49:32
【问题描述】:

一旦我确定了字段的数量,我就可以用 if 语句来编写它,但我相信 AWK 的强大功能可以简化这一点。我希望 if 语句和下面的输出中的逻辑是清晰的。

确定file1中第一个节点($2)到第二个节点(3)的链接号

if($2 && $3 (file1) == $1 and $3 (file2));
    print $2 of file2 in between $2 and $3 of file1
elif($2 && $3 (file1) == $3 && $1 (file2));
    print $4 of file2 in between $2 and $3 of file1
else
    print no_int in between $2 and $3 of file1

如果适用,确定 file1 中从第二个节点 ($3) 到第三个节点 (4) 的链接号

if($3 && $4 (file1) == $1 and $3 (file2));
    print $2 of file2 in between $2 and $3 of file1
elif($3 && $4 (file1) == $3 && $1 (file2));
    print $4 of file2 in between $3 and $4 of file1
else
    print no_int in between $3 and $4 of file1

如果适用,确定 file1 中从第三个节点 ($4) 到第四个节点 (5) 的链接号

if($4 && $5 (file1) == $1 and $3 (file2));
    print $2 of file2 in between $4 and $5 of file1
elif($4 && $5 (file1) == $3 && $1 (file2));
    print $4 of file2 in between $4 and $5 of file1
else
    print no_int in between $4 and $5 of file1  

...等等等等...

文件 1:路径表

N1-N4   NODE3   NODE4
N1-N5   NODE2   NODE4   NODE5
N1-N6   NODE3   NODE4   NODE5   NODE6

文件 2:链接表

NODE1   1   NODE2   2
NODE1   3   NODE3   4
NODE2   5   NODE4   6
NODE4   8   NODE3   7
NODE4   9   NODE5   10
NODE5   11  NODE6   12

输出:

N1-N4   NODE3   7   NODE4
N1-N5   NODE2   5   NODE4   9   NODE5   
N1-N6   NODE3   7   NODE4   9   NODE5   11 NODE6    

网络地图

NODE1--1--2--NODE2
  |            |
  3            5
  |            |
  4            6
  |            |
NODE3--7--8--NODE4--9--10--NODE5--11--12--NODE6

编辑匹配逻辑: 以file1中的一行为例:

N1-N4   NODE3   NODE4

这应该与文件二中的这一行相匹配:

NODE4   8   NODE3   7

$2 && $3 (file1) 不匹配 $1,$3 (file2) - NODE3 NODE4 != NODE4 NODE3。但是 $2,$3 确实等于 $3,$1 - NODE3 NODE4 == NODE3 NODE4。所以从 file2 打印 $4 - “NODE3 7 NODE4”。如果 $2 && $3 (file1) DID 匹配 $1,$3 (file2),从 file2 打印 $2 - "NODE3 8 NODE4"

【问题讨论】:

    标签: awk


    【解决方案1】:

    应该这样做,设置示例输入/输出以包含您感兴趣的边缘情况非常重要。

    $ awk 'NR==FNR{a[$1,$3]=$2; a[$3,$1]=$4; next} 
                  {for(i=2;i<NF;i++) 
                     {k=a[$i,$(i+1)]; 
                      $i=$i OFS (k?k:"NaN")}}1' link path
    
    
    N1-N4 NODE3 7 NODE4
    N1-N5 NODE2 5 NODE4 9 NODE5
    N1-N6 NODE3 7 NODE4 9 NODE5 11 NODE6
    

    【讨论】:

    • 虽然在这种情况下选择了最小值,但这不是我想要实现的。如果 $1,$3 == $2,$3,则使用 $2。否则 $1,$3 == $3,$2,然后使用 $4。如果用不同的逻辑编写,它会得到与你相同的输出吗?
    • 我还是不清楚,在你的比较中,($1,$3)==($2,$3) 的替代值是什么?
    • 在帖子底部添加了更好的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2014-12-25
    • 2022-01-08
    • 2018-05-17
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多