我试图编写一个循环,按照操作的顺序(而不是通常的数学优先级)计算操作,代码如下(echo用于调试):
while [[ "$(echo "$newstring"| grep -E ^-?[0-9]+$)" = "" ]]; do
oldpart="$(echo "$newstring"|cut -f1-3 -d' ')"
echo "bla $oldpart"
newpart="$(echo "$oldpart"|bc)"
echo "ble $newpart"
newstring="$(echo "$newstring"|sed -e "s/$oldpart/$newpart/")"
echo "bli $newstring"
done当将$newstring作为"6 +6*9“传递时,输出如下:
6 + 6 * 9
bla 6 + 6
ble 12
bli 12 * 9
bla 12 * 9
ble 108
bli 12 * 9
bla 12 * 9
ble 108如我们所见,6+6按预期计算为12,然后在字符串中替换。然后对12 * 9,108重新启动该操作,该操作无法替换到字符串中.而那一刻永远不会结束
我怀疑sed解释了*,这可能会阻止所需的颠覆。
知道如何绕过这种行为吗?
发布于 2020-12-18 14:07:57
一种只使用bash而不需要外部命令的解决方案
#!/bin/bash
newstring='6 + 6 * 9'
read -a atoms <<<"$newstring"
run=${atoms[0]} # Initialise running total to the first value
for ((i=1; i<=${#atoms[@]}; i+=2))
do
op=${atoms[$i]} # Next operator
num=${atoms[$((i+1))]} # Next number
run=$((run $op num)) # Perform the arithmetic (integer maths)
done
echo "$run"如果要使用浮动算术,则需要使用bc或dc。这个变体使用dc,作为在评论中建议
#!/bin/bash
newstring='6.5 + 6 * 9'
{
read -a atoms <<<"$newstring"
run=${atoms[0]}
printf "%s " "$run"
for ((i=1; i<=${#atoms[@]}; i+=2))
do
op=${atoms[$i]} num=${atoms[$((i+1))]}
printf " %s %s" "$num" "$op"
done
printf " p\n"
} | dchttps://unix.stackexchange.com/questions/625077
复制相似问题