【发布时间】:2016-01-22 22:01:18
【问题描述】:
我正在计算平均分数如下:
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
我该如何处理这个错误?
【问题讨论】:
-
你对 shell 和 awk 的糊涂太离谱了。您完全错过了使用 awk 的重点,并且不恰当地使用了 shell。至少阅读 Arnold Robbins 的《Effective Awk Programming, 4th Edition》一书的前几章,你再也不会写出那样的代码了。请参阅@TomFenech 的计算平均值的脚本,了解解决此问题的正确方法。
-
谢谢 Ed 我会确保我这样做的。