bash 从文件中读取并添加数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2572495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:08:11  来源:igfitidea点击:

read from file and add numbers

bashadd

提问by Laks

I have text file with entries like 123 112 3333 44 2

我有文本文件,其中包含 123 112 3333 44 2 之类的条目

How to add these numbers and get the sum of these.

如何将这些数字相加并得到这些数字的总和。

回答by miku

Example:

例子:

$ cat numbers.txt
123 112 3333 44 2

$ SUM=0; for i in `cat numbers.txt`; do SUM=$(($SUM + $i)); done; echo $SUM
3614

See also: Bash Programming Introduction, section on arithmetic evaluation

另请参阅:Bash 编程介绍,算术评估部分

Another way would be to use bc, an arbitrary precision calculator language:

另一种方法是使用bc,一种任意精度的计算器语言:

$ echo '123 112 3333 44 2' | tr ' ' '\n' | paste -sd+ | bc
3614

Paste usually works on lines, so we need tr.

粘贴通常适用于行,因此我们需要tr.

回答by Paused until further notice.

A Bash-only (no cat) variation on MYYN'sanswer.

MYYN答案的Bash-only (no cat) 变体。

sum=0; for i in $(<number_file); do ((sum += i)); done; echo $sum

Also, note the simpler arithmetic statement.

另外,请注意更简单的算术语句。

回答by ghostdog74

just one awk command does it. It doesn't break when you have decimals to add as well.

只需一个 awk 命令即可完成。当您要添加小数时,它也不会中断。

awk '{for(i=1;i<=NF;i++)s+=$i}END{print s}' file

回答by Jamie

Alternatively in Awk

或者在 awk 中

echo "123 112 3333 44 2" | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

Or if it's in a file

或者如果它在一个文件中

cat file.txt | awk 'BEGIN {sum=0} {for(i=1; i<=NF; i++) sum+=$i } END {print sum}'

I find Awk much easier to read/remember. Although "Dave Jarvis" solution is particular neat!

我发现 awk 更容易阅读/记忆。虽然“Dave Jarvis”的解决方案特别整洁!