Shell命令对整数求和,每行一个? [英] Shell command to sum integers, one per line?

查看:52
本文介绍了Shell命令对整数求和,每行一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个可以接受(作为输入)多行文本的命令,每行包含一个整数,并输出这些整数的总和.

I am looking for a command that will accept (as input) multiple lines of text, each line containing a single integer, and output the sum of these integers.

作为一点背景知识,我有一个日志文件,其中包括计时测量.通过搜索相关行和一些 sed 重新格式化,我可以列出该文件中的所有时间.我想算出总数.我可以将此中间输出通过管道传输到任何命令,以便进行最终求和.过去我一直使用 expr,但除非它在 ​​RPN 模式下运行,否则我认为它无法解决这个问题(即使那样也会很棘手).

As a bit of background, I have a log file which includes timing measurements. Through grepping for the relevant lines and a bit of sed reformatting I can list all of the timings in that file. I would like to work out the total. I can pipe this intermediate output to any command in order to do the final sum. I have always used expr in the past, but unless it runs in RPN mode I do not think it is going to cope with this (and even then it would be tricky).

如何得到整数的总和?

推荐答案

awk 应该怎么做?

Bit of awk should do it?

awk '{s+=$1} END {print s}' mydatafile

注意:如果您要添加超过 2^31 (2147483647) 的任何内容,某些版本的 awk 会有一些奇怪的行为.有关更多背景,请参阅评论.一种建议是使用 printf 而不是 print:

Note: some versions of awk have some odd behaviours if you are going to be adding anything exceeding 2^31 (2147483647). See comments for more background. One suggestion is to use printf rather than print:

awk '{s+=$1} END {printf "%.0f", s}' mydatafile

这篇关于Shell命令对整数求和,每行一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆