Bash ping以csv格式输出

时间:2015-11-15 13:23:04

标签: bash csv ping

我的目标是以CSV样式转换ping命令的输出(最后2行)。

以下是一些例子:

如果丢包率低于100%<

 URL, PacketLoss, Min, Average, Max, Deviation

如果丢包率等于100%

 URL, 100, -1, -1, -1, -1

我的脚本如下,但当丢包率为100%时,输出为:

URL, 100, 

所以问题出在if语句,因为它没有输入elif,我使用相同的语法来检查地址是否已满(使用&#34; www。&#34;或不)。

请你看一下,因为我尝试过多种东西而且没用。

我的剧本:

#!/bin/bash

declare site=''
declare result='';

if [[ "$1" == "www."* ]]; then
        site="$1";
else
        site="www.$1";
fi

result="$site";

pingOutput=$(ping $site -c10 -i0.2 -q| tail -n2);

fl=true;

while IFS= read -r line
do

# !!! The problem is here, the if statement is not working properly and I do not know why !!!

        if [ "$fl" == "true" ]; then
                result="$result $(echo "$line" | cut -d',' -f3 | cut -d" " -f2 | sed -r 's/%//g')";
                fl=false;
        elif [[ "$line" == "ms"* ]]; then
                result="$result $(echo "$line" | cut -d' ' -f4 | sed -r 's/\// /g')";
        else
                result="$result -1 -1 -1 -1";
        fi
done <<< "$pingOutput"

echo "$result";

2 个答案:

答案 0 :(得分:1)

由于pingOutput的第二行从未被处理过(循环在之前结束),因此从未执行过向输出添加-1的操作。

由于这个问题,我决定捕获失败的百分比,并在没有返回数据包时采取行动(100%),我还简化了你最初使用的一些表达式。

我调查了脚本并提出了以下解决方案:

#!/bin/bash

declare site=''
declare result=''
declare prctg=''

[[ "$1" == "www."* ]] && site="$1" || site="www.$1"

result="$site"

pingOutput=$(ping $site -c10 -i0.2 -q| tail -n2)

fl=true

while IFS= read -r line
do
# !!! The problem is here, the if statement is not working properly and I do not know why !!!
echo $line
if [ "$fl" == "true" ]
    then
        prctg=$(echo "$line" | grep -Po "[0-9]{0,3}(?=%)")
        result="$result $prctg"
        fl=false
    fi
if [ "$prctg" == "100" ]
    then
        result="$result -1 -1 -1 -1"
    else
        result="$result $(echo "$line" | cut -d' ' -f4 | sed -r 's/\// /g')"
    fi
done <<< "$pingOutput"

echo "$result"

答案 1 :(得分:1)

这是一个很老的问题,但是我今天偶然发现了它。在下面,我粘贴了上面脚本的略微修改后的版本,该版本解决了if问题,并且可以在Mac OS上运行。

P.S。您可以取消对# prctg=100.0%行的注释,以查看if的运行情况。

#!/bin/bash

declare site=''
declare result=''
declare prctg=''

[[ "$1" == "www."* ]] && site="$1" || site="www.$1"

result="$site"

pingOutput=$(ping $site -c10 -i0.2 -q | tail -n2)

fl=true

while IFS= read -r line
do
  #echo $line
  if [ "$fl" == "true" ]
  then
    prctg=$(echo "$line" | grep -Eo "[.[:digit:]]{1,10}%")
    result="$result,$prctg"
    fl=false
   # prctg=100.0%
  else
    if [ "$prctg" == "100.0%" ]
    then
      result="$result,-1,-1,-1,-1"
    else
      result="$result,$(echo "$line" | cut -d' ' -f4 | sed -E 's/\//,/g')"
    fi
  fi
done <<< "$pingOutput"

echo "$result"

我希望它对将来的人有所帮助! :)