使用shell脚本从一行中获取多个变量

时间:2019-04-17 18:32:45

标签: mysql bash shell

我正在尝试通过ping监视我的主机。主机信息在mysql表中。我使用fping命令的代码如下

#/bin/sh

id=$(mysql -B --column-names=0 -uroot -pPassword -D monitor -e "SELECT ipv4 FROM nics WHERE icmp=1");

result=$(fping -c 10 $id |grep 'xmt/rcv/%loss');

#echo $result;

for line in $result;

do

echo $line

done

输出为

111.125.140.6 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/235

123.135.140.7 : xmt/rcv/%loss = 10/0/100%

111.125.140.1 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 230/231/231

111.125.130.2 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/234

现在我想从每一行获取IP,损耗和平均记录,并将数据输入到新表中

预先感谢

1 个答案:

答案 0 :(得分:1)

通过while使用for循环(而不是awk循环):

while read -r line
    do declare $(awk '{split($0,a,"[%/ ,]"); print \
    "ip="a[1],"send="a[8],"rec="a[9],"loss="a[10],"min="a[17],"avg="a[18],"max="a[19]}' <<< $line);
    ## variables created: [ip, send, rec, loss, min, avg, max]
    ## test with: echo $ip, $send, $rec, $loss, $min, $avg, $max
    ## now you can insert the variables into your new SQL table:
    echo "INSERT INTO newtable (IP,SEND,REC,LOSS,MIN,AVG,MAX) \
    VALUES ('$ip','$send','$rec','$loss','$min','$avg','$max');"
done< <(printf '%s\n' "$result") | mysql -uroot -pPassword foobar

这将从您可以插入SQL的$line字符串中声明各个变量。