问题是:我有不同的 txt 文件,其中为到达服务器的每个恶意软件数据包注册了时间戳和 IP 地址。我想要做的是创建另一个 txt 文件,显示每个 ip 恶意软件数据包第一次到达的时间。
一般来说,我想做这样的事情:
for every line in file.txt
if (ip is not present in list.txt)
copy timestamp and ip in list.txt
我正在使用 awk 来完成它。主要问题是“如果 ip 不在 list.txt 中”。 我这样做:
{ a=$( grep -w "$3" list.txt | wc -c );
if ( a == 0 )
{
#copy timestamp and ip in list.txt
}
(我使用 $3 因为 IP 地址在源文件的第三列)
我不知道如何让 awk 计算 grep 函数。我也试过反引号,但没有用。有人可以给我一些提示吗?
我正在像这样在测试文件上测试我的脚本:
10 192.168.1.1
11 192.168.1.2
12 192.165.2.4
13 122.11.22.11
13 192.168.1.1
13 192.168.1.2
13 122.11.22.11
14 122.11.22.11
15 122.11.22.11
15 122.11.22.144
15 122.11.2.11
15 122.11.22.111
我应该得到的是:
10 192.168.1.1
11 192.168.1.2
12 192.165.2.4
13 122.11.22.11
15 122.11.22.144
15 122.11.2.11
15 122.11.22.111
感谢您的帮助,我成功地创建了符合我需要的脚本:
awk '
FILENAME == ARGV[1] {
ip[$2] = 1
next
}
! ($2 in ip) {
print $1, $2 >> ARGV[1]
ip[$2] = 1
}
' list.txt file.txt
最佳答案
将问题解释为“我如何从 awk 中评估命令的状态?”,只需使用 system。
{ if( system( "cmd" ) == 0 ) { # the command succeeded { }
因此,在您的情况下,只需执行以下操作:
{ if( system( "grep -w \"" $3 "\" list.txt > /dev/null " ) == 0 ) { ... } }
不过,您可能需要重新考虑您解决问题的方法。 Grepping 每次都在计算上很昂贵,并且有更好的方法 处理问题。 (例如,将 list.txt 读入数组一次。)
另请注意,您不需要使用 wc。如果没有,则 grep 失败 匹配字符串。使用返回值而不是解析输出。
关于awk - 使用 Awk 评估命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741700/