如何计算linux中的平均值?
I have a file like this: ID Math Sci Eng Average 230 70 - 50 123 50 50 60 223 - 80 90
我需要这样的输出:
ID Math Sci Eng Average 230 70 - 50 60 123 50 50 60 53.33 223 - 80 90 85
我正在使用此代码,但我只能获得总数:
awk '/^[0-9]/ {for (i=2; i<=NF; i++) {tot+=$i}; avg=tot/cnt[i]; print $1 "\t" avg}'
我用以上计算总计;并且以为我能算数。但它给了我一个错误..请帮助我,我是这个领域的新手..谢谢:)。
答案 0 :(得分:1)
awk '/^[0-9]/ {
tot = 0;
count = 0;
for (i = 2; i <= NF; i++) {
to += $i;
if($i + 0 == $i){
count++;
}
}
avg = tot/count;
print $0,avg;
}'
最好将它放入脚本中。
答案 1 :(得分:0)
:
filename = '/tmp/input'
outfile = '/tmp/output'
first = true
out = File.open(outfile, 'w')
File.readlines( filename ).each do |line|
arr = line.split
if first
out.puts line
first = false
else
sum = 0
arr[1..3].each{|x| sum += x.to_i }
denom = arr[1..3].count{|x| x =~ /\d+/ }
avg = sum / denom.to_f
arr << avg
out.puts arr.join(' '*10)
end
end
out.close
答案 2 :(得分:0)
AWK
脚本:awk '
/^[0-9]/{
total=0;
count=0;
for(i=2;i<=NF;i++)
{
total=total+$i;
if($i!="-")
{
count++;
}
}
print $0"\t\t" total/count
}
!/[0-9]/{
print $0;
next
}' avg.txt
[jaypal~/Temp]$ cat avg.txt
ID Math Sci Eng Average
230 70 - 50
123 50 50 60
223 - 80 90
[jaypal:~/Temp] awk '
/^[0-9]/{
total=0;
count=0;
for(i=2;i<=NF;i++)
{
total=total+$i;
if($i!="-")
{
count++;
}
}
print $0"\t\t" total/count
}
!/[0-9]/{
print $0;
next
}' avg.txt
ID Math Sci Eng Average
230 70 - 50 60
123 50 50 60 53.3333
223 - 80 90 85