我如何能快速总结所有号码在一个文件? [英] How can I quickly sum all numbers in a file?
问题描述
我有一个包含几千个数字的文件中,每个在它自己的行:
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?
推荐答案
有关一个Perl一行程序,它基本上是同样的事情在<一对 AWK
解决方案href=\"http://stackoverflow.com/questions/2702564/script-to-sum-all-numbers-in-a-file-linux/2702577#2702577\">Ayman Hourieh的回答:
For a Perl one-liner, it's basically the same thing as the awk
solution in Ayman Hourieh's answer:
% perl -nle '$sum += $_ } END { print $sum'
如果你好奇的俏皮话做什么Perl中,你可以deparse他们:
If you're curious what Perl one-liners do, you can deparse them:
% perl -MO=Deparse -nle '$sum += $_ } END { print $sum'
结果是该计划的更详细的版本,在一个形式,没有人会写自己的:
The result is a more verbose version of the program, in a form that no one would ever write on their own:
BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
chomp $_;
$sum += $_;
}
sub END {
print $sum;
}
-e syntax OK
只是为了笑声,我想这与含(范围为0 - 9,999)百万数量的文件。在我的Mac Pro,它返回几乎瞬间。这太糟糕了,因为我希望用 MMAP
会非常快,但它只是在同一时间:
Just for giggles, I tried this with a file containing 1,000,000 numbers (in the range 0 - 9,999). On my Mac Pro, it returns virtually instantaneously. That's too bad, because I was hoping using mmap
would be really fast, but it's just the same time:
use 5.010;
use File::Map qw(map_file);
map_file my $map, $ARGV[0];
$sum += $1 while $map =~ m/(\d+)/g;
say $sum;
这篇关于我如何能快速总结所有号码在一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!