我有一个包含数千个数字的文件,每个数字都在自己的行上:

34
42
11
6
2
99
...

我想写一个脚本,它将打印文件中所有数字的总和。我有一个解决办法,但不是很有效。(运行需要几分钟。)我在寻找一个更有效的解决方案。有什么建议吗?


当前回答

sed ':a;N;s/\n/+/;ta' file|bc

其他回答

我还没有测试,但它应该工作:

cat f | tr "\n" "+" | sed 's/+$/\n/' | bc

如果bc不处理EOF和EOL,你可能必须在bc之前添加“\n”到字符串(比如通过echo)…

sed ':a;N;s/\n/+/;ta' file|bc

c++“俏皮话”:

#include <iostream>
#include <iterator>
#include <numeric>
using namespace std;

int main() {
    cout << accumulate(istream_iterator<int>(cin), istream_iterator<int>(), 0) << endl;
}
$ perl -MList::Util=sum -le 'print sum <>' nums.txt

更简洁:

# Ruby
ruby -e 'puts open("random_numbers").map(&:to_i).reduce(:+)'

# Python
python -c 'print(sum(int(l) for l in open("random_numbers")))'