gpt4 book ai didi

linux - 根据唯一列合并两个列表文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:24 26 4
gpt4 key购买 nike

我有两个文件,一个名为 NATLog,有 3 列,另一个名为 Sourceports,有 2 列,下面是 NATLog 文件的示例。

NAT日志

14 172.18.2.12 445 
50 172.18.24.4 123
80 10.2.123.37 22
68 172.18.1.37 25

我想将 NATLog 文件的最后一列与 Sourceports 文件的第一列相匹配,并将关联的服务附加到 NATLog 文件作为第 4 列

源端口

445 SMB
123 Network Time Protocol (NTP)
22 SSH
25 SMTP(Insecure)

期望的输出

14 172.18.2.12 445 SMB 
50 172.18.24.4 123 Network Time Protocol (NTP)
80 10.2.123.37 22 SSH
68 172.18.1.37 25 SMTP(Insecure)

我正在努力学习 AWK 来完成这个,但我需要一些帮助,你能帮帮我吗,谢谢

最佳答案

awk 中的另一个(好吧,实际上是两个)。这是为了完美的世界:

$ awk 'NR==FNR{a[$1]=$0;next}{sub($NF,a[$NF])}1' source natlog
14 172.18.2.12 445 SMB
50 172.18.24.4 123 Network Time Protocol (NTP)
80 10.2.123.37 22 SSH
68 172.18.1.37 25 SMTP(Insecure)

解释(并针对不完美的世界进行了一些扩展):

$ awk '
NR==FNR { # processing the source file
# gsub(/&/,"\\\\&") # if & chars in the file, uncomment to escape them
a[$1]=$0 # hash to a, port is the key
next
}
{ # process natlog file
sub($NF,a[$NF]) # replace port field with entry from source file
# sub($NF,(a[$NF]?a[$NF]:$NF)) # if gaps in source, use this instead of above
}1' source natlog

一个可能的输出(源中较短的 ip、& 字符和不匹配的端口 222):

14 1.18.2.12   445 SMB & 
50 172.18.24.4 123 Network Time Protocol (NTP)
80 10.2.123.37 222
68 172.18.1.37 25 SMTP(Insecure)

关于linux - 根据唯一列合并两个列表文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55109852/

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