I'm trying to write a loop that computes operations in the order they come (not the usual mathematical precedence) The code goes like this (echo is for debugging):
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
Output is the following when passed $newstring as "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
As we can see, 6 + 6 is calculated as 12 as expected, then replaced in the string. The operation then restarts for 12 * 9, 108 - which fails to replace into the string... and the while never ends
I suspect sed interprets the * which might prevent the desired substition.
Any idea how to bypass that behaviour?
*
is part of basic regular expressions and thus is interpreted. Better to change the approach. Are elements always separated by space in the input expression, or is1+1
valid? Are only elementary operations supported or should it computelog(sin(4))
?dc
. Your example translates toecho "6 6 + 9 * p" | dc