我在awk文件中得到-nan输出,同时划分两个整数

时间:2016-11-27 05:31:39

标签: awk

代码:

BEGIN {
    sent=0;
    received=0;
    event=$1;
}
{
    if(event=="s") sent++;
    else if(event=="r") received++;
}
END {
    printf "\n Packet Delivery Ratio: %.2f ", (sent/received)*100;
}

输出:

数据包传送率:-nan

我想删除-nan并显示正确的输出。

2 个答案:

答案 0 :(得分:1)

您正在event块中设置BEGIN变量,因此它不会获得与当前行对应的值。将分配移动到中间块:

BEGIN {
    sent=0;
    received=0;
}
{
    event=$1;
    if(event=="s") sent++;
    else if(event=="r") received++;
}
END {
    printf "Packet Delivery Ratio: %.2f\n", (received/sent)*100;
}

请注意,脚本可以用这样的方式写一点:

{ event = $1 }
event == "s" { sent++ }
event == "r" { received++ }
END {
    printf "Packet Delivery Ratio: %.2f\n", (received/sent)*100
}

另请注意,数据包传送率的公式不正确。您应该将接收/发送分开以获得正确的值。

答案 1 :(得分:1)

让我们更简单:

($1=="s"){sent++}
($1=="r"){received++}
END{printf("\n Packet Delivery Ratio: %.2f ", (received/sent)*100)}