从文件读取浮点数并将它们添加到unix shell脚本中
问题描述:
我有一个文件temp.txt。浮点值在那里。从文件读取浮点数并将它们添加到unix shell脚本中
cat temp.txt
43.51
26.52
63.31
21.36
1.01
13.91
19.64
30.98
我想添加这些值。
请有人帮我解决这个问题。
答
awk '{s+=$0}END{print s}' tmp.txt
kent$ echo "43.51
26.52
63.31
21.36
1.01
13.91
19.64
30.98"|awk '{s+=$0}END{print s}'
220.24
答
这里有一个基于 'BC' 版本:
#!/usr/bin/env bash
tally=0
while read value
do
tally=`echo "scale=3;${value} + ${tally}" | bc`
done < tmp.txt
其中tmp.txt包含:
43.51
26.52
63.31
21.36
1.01
13.91
19.64
30.98
运行输出是:
./script-math
220.24
可以修改成为:
#!/usr/bin/env bash
tally=0
while read value
do
tally=`echo "scale=3;${value} + ${tally}" | bc`
done
所以,你可以:
cat tmp.txt | ./script-math
答
尝试这种短变体
paste -sd+ temp.txt|bc
发现在广义含方式:) #/斌/庆典 文件答案=” /basepath/temp.txt“ sum ='awk'{for(i = 1; i sasuke 2013-04-25 17:43:23
@sasuke你评论中的awk行不适用于你的temp.txt。每行有一个数字。您找到的awk行将所有数字都在一行中,并以空格分隔 – Kent 2013-04-25 17:47:40