How can I quickly sum all numbers in a file?

2020-01-24 03:22发布

I have a file which contains several thousand numbers, each on it's own line:

34
42
11
6
2
99
...

I'm looking to write a script which will print the sum of all numbers in the file. I've got a solution, but it's not very efficient. (It takes several minutes to run.) I'm looking for a more efficient solution. Any suggestions?

27条回答
女痞
2楼-- · 2020-01-24 04:11

You can use awk:

awk '{ sum += $1 } END { print sum }' file
查看更多
够拽才男人
3楼-- · 2020-01-24 04:12

Just for fun, lets do it with PDL, Perl's array math engine!

perl -MPDL -E 'say rcols(shift)->sum' datafile

rcols reads columns into a matrix (1D in this case) and sum (surprise) sums all the element of the matrix.

查看更多
\"骚年 ilove
4楼-- · 2020-01-24 04:12

Here's another:

open(FIL, "a.txt");

my $sum = 0;
foreach( <FIL> ) {chomp; $sum += $_;}

close(FIL);

print "Sum = $sum\n";
查看更多
登录 后发表回答