我有一个包含数千个数字的文件,每个数字都在自己的行上:
34
42
11
6
2
99
...
我想写一个脚本,它将打印文件中所有数字的总和。我有一个解决办法,但不是很有效。(运行需要几分钟。)我在寻找一个更有效的解决方案。有什么建议吗?
我有一个包含数千个数字的文件,每个数字都在自己的行上:
34
42
11
6
2
99
...
我想写一个脚本,它将打印文件中所有数字的总和。我有一个解决办法,但不是很有效。(运行需要几分钟。)我在寻找一个更有效的解决方案。有什么建议吗?
当前回答
c++“俏皮话”:
#include <iostream>
#include <iterator>
#include <numeric>
using namespace std;
int main() {
cout << accumulate(istream_iterator<int>(cin), istream_iterator<int>(), 0) << endl;
}
其他回答
对于这样的任务,我更喜欢使用GNU数据集,因为它比perl或awk更简洁易读。例如
datamash sum 1 < myfile
其中1表示数据的第一列。
更简洁:
# Ruby
ruby -e 'puts open("random_numbers").map(&:to_i).reduce(:+)'
# Python
python -c 'print(sum(int(l) for l in open("random_numbers")))'
这是直接的Bash:
sum=0
while read -r line
do
(( sum += line ))
done < file
echo $sum
在shell中使用awk,我使用下面的脚本来这样做:
#!/bin/bash
total=0;
for i in $( awk '{ print $1; }' <myfile> )
do
total=$(echo $total+$i | bc )
((count++))
done
echo "scale=2; $total " | bc
另一个是为了好玩
sum=0;for i in $(cat file);do sum=$((sum+$i));done;echo $sum
或者再来一次
s=0;while read l; do s=$((s+$l));done<file;echo $s
但awk解决方案可能是最好的,因为它最紧凑。