Bash 如何将计算结果添加到变量
stdin是Bash 如何将计算结果添加到变量,bash,Bash,stdin是 1\n2\n3 我试着把每个数字都提高到3的幂,然后把它们的总和加在$count上 我想跑的是什么 xargs -I %var sh -c 'math stuff and increasing $count here???' 那么: powr=3 # Set the power in a variable powr printf "1\n2\n3" | awk -v powr=$powr '{ pow=$1^powr;count=count+pow } E
1\n2\n3
我试着把每个数字都提高到3的幂,然后把它们的总和加在$count上
我想跑的是什么
xargs -I %var sh -c 'math stuff and increasing $count here???'
那么:
powr=3 # Set the power in a variable powr
printf "1\n2\n3" | awk -v powr=$powr '{ pow=$1^powr;count=count+pow } END { print count }'
从输入中取出每一行,计算功率(pow),加上一个计数。最后,打印总计数。如果所有数字都是整数,那么:
#!/bin/bash
pow=3 # raise inputs to the power of 3
count=0 # whatever pre-defined value
[[ -t 0 ]] && echo "Input number and press enter key. Type Ctrl-D when you are done."
# show the message if stdin is console input
while IFS= read -r i; do # read the input line by line
(( sum += i ** pow )) # accumulate the exponentiations
done
(( count += sum )) # add to the $count
echo "count = $count"
调用上述脚本时,请尝试从stdin输入数字和Ctrl+D。请注意,
bash
通常不适用于数学计算。上面的代码是一个小计算的演示。Btw:您可以使用pow=$1**3
或pow=$1^3
,谢谢!它是有效的,如果我想把它提升到一个在命令外声明的变量,我该怎么做呢?你可以用-v把变量传递到awk中。我已经修改了答案,以显示您可以如何传递权力,不用担心。如果你能接受答案,那就太好了。awk-v powr=$powr'{count+=$1^powr}END{print count}'