我有包含 IP 列表的文件:
1.1.1.1
2.2.2.2
3.3.3.3
5.5.5.5
1.1.1.1
5.5.5.5
Run Code Online (Sandbox Code Playgroud)
我想创建打印上述 IP 的计数器列表的文件,例如:
1.1.1.1: 2
2.2.2.2: 1
3.3.3.3: 1
5.5.5.5: 2
Run Code Online (Sandbox Code Playgroud)
其中 2,1,1,2 是计数器。
我开始编写适用于最终计数 IP 和已知计数的脚本,但不知道如何继续
./ff.sh file_with_IPs.txt
Run Code Online (Sandbox Code Playgroud)
脚本
#!/bin/sh
file=$1
awk '
BEGIN {
for(x=0; x<4; ++x)
count[x] = 0;
ip[0] = "1.1.1.1";
ip[1] = "2.2.2.2";
ip[2] = "3.3.3.3";
ip[3] = "5.5.5.5";
}
{
if($1==ip[0]){
count[0] += 1;
} else if($1==ip[1]){
count[1] += 1;
}else if($1==ip[2]){
count[2] += 1;
}else if($1==ip[3]){
count[3] += 1;
}
}
END {
for(x=0; x<4; ++x) {
print ip[x] ": " count[x]
}
}
' $file > newfile.txt
Run Code Online (Sandbox Code Playgroud)
主要问题是我不知道文件中存储了多少个 IP 以及它们是什么样子。
ip所以每次 awk 捕获新 IP 时我都需要增加数组。
我认为使用 更容易sort -u,但是使用 awk 可以做到这一点:
awk '{a[$0]++; next}END {for (i in a) print i": "a[i]}' file_with_IPs.txt
Run Code Online (Sandbox Code Playgroud)
输出:
1.1.1.1: 2
3.3.3.3: 1
5.5.5.5: 2
2.2.2.2: 1
Run Code Online (Sandbox Code Playgroud)
(在sudo_O 推荐我的本教程的一点帮助下)