gpt4 book ai didi

awk 比较三个文件中的列并打印不匹配的带有 NA 前缀的列及其内容

转载 作者:行者123 更新时间:2023-12-04 02:30:05 24 4
gpt4 key购买 nike

嗨,我有一个问题要解决三个文件的比较以获得所需的输出,其中 file1 列 $2 与 file2 列 $4 以及 file3 列 $2 进行比较 其中是结果它将附加到 file1 的输出文件名加上将从 file1 打印不匹配的列连同添加的 NA 以反射(reflect)剩余的列以保持它们的完整/一致

文件1

4 FIX VAL1 32254720
0 AA SILO_T 4294967290
16 RS SILO 2684560000
3 DD SILO_A 1041824000
2 BB SILO_B 4294729600

文件2

377 le377 4 FIX cell 0x
514 le514 3 DD cell 0c
0 le0 2 BB cell 2a
516 le516 0 AA cell 8c

文件3

3 DD SILO_A 100 on 0 yes
2 BB SILO_B 400 on 0 no
0 AA SILO_T 3 on 0 yes
4 FIX VAL1 30 on 0 no

输出应该是:

file1 4 FIX VAL1 32254720 377 le377 4 FIX cell 0x 4 FIX 30 on 0 no
file1 0 AA SILO_T 4294967290 516 le516 AA cell 8c 0 AA 3 on 0 yes
file1 16 RS SILO 2684560000 NA NA NA NA NA NA NA NA NA NA NA
file1 3 DD SILO_A 1041824000 514 le514 3 DD cell 0c DD 100 on 0 yes
file1 2 BB SILO_B 4294729600 0 le0 2 BB cell 2a BB 400 on 0 no

部分工作代码

awk 'FNR==NR{a[$3]=$0;next}; \
{printf FILENAME "%s %s %s %s %s %s\n","",$1,$2,$3,$4,$5 (($1 in a)?a[$1]: "NA NA NA NA NA NA")}' file2 file1

file1 4 FIX VAL1 32254720 377 le377 4 FIX cell 0x
file1 0 AA SILO_T 4294967290 516 le516 0 AA cell 8c
file1 16 RS SILO 2684560000 NA NA NA NA NA NA
file1 3 DD SILO_A 1041824000 514 le514 3 DD cell 0c
file1 2 BB SILO_B 4294729600 0 le0 2 BB cell 2a

我不知道如何传递 file3 进行下一次比较以完成工作以获得所需的输出,如果提供的解决方案带有解释我会很高兴这样我可以完全理解在需要的情况下如何交换列号另一个需要在未来进行比较,感谢您提供任何帮助,如何扩展当前代码或将其编写得更简单

最佳答案

你可以使用这个 awk 脚本:

cat mergeall.php

BEGIN {
fill = "NA NA NA NA NA NA NA NA NA NA NA NA NA"
}
ARGIND == 1 { # while processing 1st file in arguments
map[$4] = $0
next
}
ARGIND == 2 { # while processing 2nd file in arguments
map[$2] = ($2 in map ? map[$2] OFS : "") $0
next
}
{ # while processing 3rd file in arguments
print FILENAME, $0, ($2 in map ? map[$2] : fill)
}

然后将其用作:

awk -f mergeall.awk file2 file3 file1 | column -t
file1  4   FIX  VAL1    32254720    377  le377  4   FIX  cell  0x  4   FIX  VAL1    30   on  0   no
file1 0 AA SILO_T 4294967290 516 le516 0 AA cell 8c 0 AA SILO_T 3 on 0 yes
file1 16 RS SILO 2684560000 NA NA NA NA NA NA NA NA NA NA NA NA NA
file1 3 DD SILO_A 1041824000 514 le514 3 DD cell 0c 3 DD SILO_A 100 on 0 yes
file1 2 BB SILO_B 4294729600 0 le0 2 BB cell 2a 2 BB SILO_B 400 on 0 no

请注意,我们按以下顺序输入文件:file2 file3 file1

关于awk 比较三个文件中的列并打印不匹配的带有 NA 前缀的列及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64796946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com