在awk中除以零值

时间:2016-01-22 13:41:56

标签: math awk division

我正在计算平均得分如下:

average_score=$(awk "BEGIN {printf \"%.2f\",${sum_of_score}/${number_of_lines}}")

其中sum_of_scores按每个greped ID计算如下:

sum_of_score=$(grep 271712:E1 M10.6.txt | awk '{s+=$5} END {print s}')

number_of_lines=$(grep 271712:E1 M10.6.txt | awk 'END{print FNR}')

然而有时sum_of_score和/或number_of_lines的值可能为零,因此我收到错误:

awk: BEGIN {printf "%.2f",/0}
awk:                       ^ unterminated regexp
awk: cmd. line:1: BEGIN {printf "%.2f",/0}
awk: cmd. line:1:                         ^ unexpected newline or end of string

如何处理此错误?

1 个答案:

答案 0 :(得分:5)

您的sum_of_score变量应按如下方式计算:

sum_of_score=$(awk '/271712:E1/ { sum += $5 } END { print sum + 0 }')

+ 0表示sum在数字上下文中进行评估,因此空sum0而不是空字符串。

如果您只想要平均值(平均值),请执行以下操作:

awk '/271712:E1/ { sum += $5; ++count } END { if (count) print sum / count }'

如果if (count)没有增加0,则count会阻止除#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from urllib import quote_plus name = u'Mayte_Martín' quote_plus(name.encode('utf-8'), safe=':/'.encode('utf-8'))

你的"除以零"错误与除以零实际上没有任何关系;他们的语法错误。每个错误中的消息都描述了错误!

相关问题