读取数字,然后将它们添加到循环中。Bash/Linux
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18591095/
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
Reading in numbers, then adding them in a loop. Bash/Linux
提问by John Doe
Help!
帮助!
I am having big problems finding out how to add numbers that i've written in(read) a loop. The task im supposed to do is to add X amount of numbers(which I must use read for) then adding them all when "Ctrl+d" is pressed. Im fairly new to linux so please make it as simple as possible :)
我在找出如何添加我在(读取)循环中写入的数字时遇到了大问题。我应该做的任务是添加 X 数量的数字(我必须使用 read ),然后在按下“Ctrl + d”时将它们全部添加。我对 linux 还很陌生,所以请尽可能简单:)
回答by lulyon
#!/bin/bash
sum=0
while read num;
do
let sum=sum+num;
done
echo $sum
Command:
命令:
./script.sh
Input:
输入:
1
2
3
4
5
ctrl+D
Output:
输出:
15
回答by sehe
My favorite trick here employs bc
:
我最喜欢的技巧是bc
:
xargs -n1 | paste -sd+ | bc
Though you could use bash evaluation if you don't want to use bc
:
虽然如果您不想使用,您可以使用 bash 评估bc
:
sum=$(($(xargs -n1 | paste -sd+)))
echo $sum
回答by konsolebox
#!/bin/bash
shopt -s extglob
SUM=0
while read NUM && [[ $NUM == +([[:digit:]]) ]]; do
(( SUM += NUM ))
done
echo "$SUM"
回答by Bluewind
Assuming your input contains one number per line and nothing else, something like this should work:
假设您的输入每行包含一个数字,没有其他内容,这样的事情应该可以工作:
cat $file | tr "\n" "+" | tr -d " " | sed 's/\+$/\n/' | bc
(Useless use of cat: This is a example and therefore cat $file represents anything that might output one number per line)
(cat 的无用使用:这是一个例子,因此 cat $file 代表任何可能每行输出一个数字的东西)
If your numbers aren't integers, you can add the -l option to bc which will enable among other things floating point support.
如果您的数字不是整数,您可以将 -l 选项添加到 bc,这将启用浮点支持等。