我有一个带有我想要使用fping
检查的IP列表的txt,然后将IP转换为名称。
我的文件(hosts.txt
)如下所示:
192.168.1.1 serverA
192.168.1.2 serverB
192.168.1.3 serverC
这是我写的脚本:
#! /bin/bash
N_Hosts=$(wc hosts.txt | awk {'print $1'})
typeset Nodos[$N_Hosts]
i=0;
while read line
do
Nodos[$i]=$(echo $line | awk {'print $1'})
i=$i+1
done < hosts.txt
comando="fping "
comandoCompleto=$comando${Nodos[*]}
$comandoCompleto | sed 's/is alive/OK/g' | sed 's/is unreachable/down/g'
它的输出如下:
192.168.1.1 OK
192.168.1.2 down 192.168.1.3确定
我希望如此:
serverA OK
serverB down
serverC OK
是否可以使用sed
或awk
?
答案 0 :(得分:3)
如果您有两个文件,即hosts.txt和output.txt(从脚本输出),那么您可以这样做:
awk 'NR==FNR{a[$1]=$2;next}{$1=a[$1]}1' hosts.txt output.txt
答案 1 :(得分:1)
完全在awk(我认为这需要gawk)
gawk '
{
name[$1] = $2
ips = ips " " $1
}
END {
while ((("fping" ips) | getline) != 0) {
if ($3 == "alive")
print name[$1] " OK"
else if ($3 == "unreachable")
print name[$1] " down"
}
}
' hosts.txt
或完全使用bash版本4
declare -a ips
declare -A names
while read ip name; do
ips+=($ip)
names[$ip]=$name
done < hosts.txt
fping "${ips[@]}" |
while read ip _ status; do
case $status in
alive) echo ${names[$ip]} OK ;;
unreachable) echo ${names[$ip]} down ;;
esac
done
答案 2 :(得分:1)
sed -r 's#(\S+)\s+(\S+)#/\1/s/(\\S+)\\s+(\\S+)/\2 \\2/#' hosts.txt|sed -rf - output.txt
..输出:
serverA OK serverB down serverC OK
答案 3 :(得分:0)
听起来你只需要:
while read ip name
do
fping "$ip" |
awk -v n="$name" '{print n, (/alive/?"OK":"down")}'
done < hosts.txt