printf - bash:如何总结读取命令中的间隔数?
问题描述
例如:
#!/bin/bash
printf '%s' "write 4 numbers separated by spaces:"
read -r var
# suppose to print sum of calculated numbers, in this case I want to calculate like this:
# ((1n*2n)+(3n*4n))/2 <----divided by (total item/2)
exit 0
所以,假设我们在执行代码时输入了 4 个数字,让我们输入 ,11 22 33 44.4
然后,如果我没记错的话enter
,我们得到了结果。853.6
解决方案
从那长长的列表中,我选择了bc,因为它是我喜欢的:
#!/bin/bash
wanted_numbers=4
read -p "write ${wanted_numbers} numbers separated by spaces: " line
#echo "debug: line >$line<" >&2
result=0
numbers=0
while read var
do
#echo "debug: got >$var<" >&2
result=$(bc <<< "${result}+${var}")
numbers=$((numbers + 1))
done < <(tr ' ' '\n' <<< $line)
if [[ $numbers != $wanted_numbers ]]; then
echo "I asked for ${wanted_numbers} numbers and got ${numbers}. Try again..." >&2
exit 1
fi
echo $result
从这里开始,您可以做任何您需要做的事情${result}
。如果您需要用实数进行除法,bc是您的朋友。
最棘手的部分是您看到的进程替换done < <(...)
,以便能够在while
循环中设置变量,否则将是一个子shell,并在循环外提供结果。
推荐阅读
- c++ - 单击或拖动标题栏时如何防止计时器冻结?
- android-studio - android studio中的gridlayout有问题
- benchmarking - 当我安装 SPEC2006 时,它不会执行此步骤
- node.js - Odata $filter 总是返回带有节点 js 和 postgresql 的空数组
- javascript - 如何在画布上重复绘制?
- go - 来自天蓝色管道工件的自定义处理程序 defaultExecutablePath
- java - 查找两个特殊符号之间的字符数
- r - 是否有一个函数可以根据另一列的条件替换列中的特定值?
- sed - 如何使用 sed 在文件中的特定行附加数据,其中数据来自另一个文件
- xaml - UWP-CPP/Winrt 使 ListViewItem 数据模板的 Line Control 仅在选中时可见