bash-发现在行号的平均 [英] bash- find average of numbers in line
问题描述
我试图读取文件里逐行并找到数的平均值中的每一行。我收到错误: expr的:非数值参数
我已经缩小问题降到总结= EXPR $总和+ $ I
,但我不知道为什么code不起作用。
同时读取-a行
做
因为我在$ {行[@]}
做
总和=`$ expr的总和+ $ i`
总=`$ expr的总+ 1`
DONE
平均=`$ expr的总和/ $ total`
完成< $文件名
文件看起来像这样(数字由制表符分隔):
1 1 1 1 1
9 3 4 5 5
6 7 8 9 7
3 6 8 9 1
3 4 2 1 4
6 4 4 7 7
通过一些小的修改,你的code运行良好:
同时读取-a行
做
总= 0
总和= 0
因为我在$ {行[@]}
做
总和=`$ expr的总和+ $ i`
总=`$ expr的总+ 1`
DONE
平均=`$ expr的总和/ $ total`
回声$平均
完成<文件名
通过样本输入文件,产生的输出是:
1
五
7
五
2
五
请注意,答案是它们是什么,因为 EXPR
只做整数运算。
使用sed来preprocess expr的
以上code可以被改写为:
$同时读取行;做EXPR'('$(SED的/ * / + / G'<<<$行)')'/ $(WC -w<<< $行);完成<文件名
1
五
7
五
2
五
使用bash的内建运算能力
EXPR
是过时了。在现代的bash:
同时读取-a行
做
总= 0
总和= 0
因为我在$ {行[@]}
做
((总和+ = $ i)条)
((总++))
DONE
回声$((金额/总))
完成<文件名
使用awk的浮点运算
由于awk并浮点运算,它可以提供更准确的结果:
$的awk'{S = 0;对于(i = 1; I< = NF;我++)S + = $ I;打印S / NF;}'文件名
1
5.2
7.4
5.4
2.8
5.6
I am trying to read a file line by line and find the average of the numbers in each line. I am getting the error: expr: non-numeric argument
I have narrowed the problem down to sum=expr $sum + $i
, but I'm not sure why the code doesn't work.
while read -a rows
do
for i in "${rows[@]}"
do
sum=`expr $sum + $i`
total=`expr $total + 1`
done
average=`expr $sum / $total`
done < $fileName
The file looks like this (the numbers are separated by tabs):
1 1 1 1 1
9 3 4 5 5
6 7 8 9 7
3 6 8 9 1
3 4 2 1 4
6 4 4 7 7
With some minor corrections, your code runs well:
while read -a rows
do
total=0
sum=0
for i in "${rows[@]}"
do
sum=`expr $sum + $i`
total=`expr $total + 1`
done
average=`expr $sum / $total`
echo $average
done <filename
With the sample input file, the output produced is:
1
5
7
5
2
5
Note that the answers are what they are because expr
only does integer arithmetic.
Using sed to preprocess for expr
The above code could be rewritten as:
$ while read row; do expr '(' $(sed 's/ */ + /g' <<<"$row") ')' / $(wc -w<<<$row); done < filename
1
5
7
5
2
5
Using bash's builtin arithmetic capability
expr
is archaic. In modern bash:
while read -a rows
do
total=0
sum=0
for i in "${rows[@]}"
do
((sum += $i))
((total++))
done
echo $((sum/total))
done <filename
Using awk for floating point math
Because awk does floating point math, it can provide more accurate results:
$ awk '{s=0; for (i=1;i<=NF;i++)s+=$i; print s/NF;}' filename
1
5.2
7.4
5.4
2.8
5.6
这篇关于bash-发现在行号的平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!