这是我的输入文件的一些行:
08:51:36 UN 127.0.0.1
08:51:36 UN 127.0.0.2
08:51:36 UN 127.0.0.3
08:53:50 DN 127.0.0.1
08:53:50 DN 127.0.0.2
08:53:50 DN 127.0.0.3
我想编写一个 shell 脚本,其中输入 ip 地址
./CountRate.sh 127.0.0.1
该脚本必须返回 0.5。公式为: IP 127.0.0.1 的节点处于 UN 状态(“1”)的次数除以 127.0.0.1(“2”)出现的行数。我必须使用哪些 Linux 命令才能实现此目的?
答案1
脚本awk
语言可以轻松做到这一点:
awk -v host=127.0.0.1 '
$3 == host {n++; x += $2 == "UN" ? 1 : 0}
END {print x/n}
' inputfile
0.5
答案2
下面的脚本使用两个参数:(IP 地址和输入文件名)
#!/bin/bash
echo "IP address: $1"
echo "Input file name: $2"
Count_IP=$(grep -c "$1" "$2" )
Count_IP_UN=$(grep "$1" "$2" |grep -c "UN")
echo "IP Count: $Count_IP"
echo "IP Count with UN: $Count_IP_UN"
Result=$(bc <<< "scale=1; $Count_IP_UN/$Count_IP"| awk '{printf "%0.1f", $0}')
echo "The result is: $Result"
执行示例:
$ ./CountRate.sh 127.0.0.1 inp.txt
IP address: 127.0.0.1
Input file name: inp.txt
IP Count: 2
IP Count with UN: 1
The result is: 0.5