I am new with scripting and I want to write a script that has to process it's argument(s) as following:
$ tandenstokers "| | x|| | |+|"
|| x |||| + | = 9 (11 tandenstokers)
$ tandenstokers \| \| x\|\| \| \|\+\|
|| x |||| + | = 9 (11 tandenstokers)
Where as I get this as output:
$ tandenstokers \| \| x\|\| \| \|\+\|
|| x |||| + | = 0 (0 tandenstokers)
What it does is basically count the amount of 'sticks' and apply simple maths to it. The resulting output is: 1. The given argument(s) with only spaces left before and after an x or + 2. 9 in the example above is the result of the maths. 3. 11 is the amount of sticks used in the formula (a + and a x count as two sticks)
So far I have the following code, and I don't understand where my mistake is:
#!/bin/bash
uitdrukking="$*"
size=${#uitdrukking}
mooi=$(echo "$uitdrukking" | sed -e 's/ //g' | sed -e 's/+/ + /g' | sed -e 's/x/ x /g')
x=0
y=1
a=1
n=0
m=0
sub=0
while [ $a -le $size ]
do
((a++))
if [ ${uitdrukking:$x:$y} -eq "|" ]
then
((n++))
((x++))
((y++))
((m++))
elif [ ${uitdrukking:$x:$y} -eq "+" ]
then
((x++))
((y++))
m=$[ $m + 2 ]
elif [ ${uitdrukking:$x:$y} -eq "x" ]
then
((x++))
((y++))
m=$[ $m + 2 ]
while [ ${uitdrukking:$x:$y} -eq "|" ]
do
((sub++))
((x++))
((y++))
((m++))
done
n=$[ $n * $sub ]
else
((x++))
((y++))
fi
done
echo "$mooi = $n ($m tandenstokers)"
Solved this problem by starting from scratch with a different approach, which resulted in the following correct code:
#!/bin/bash
echo "$(echo "$*" | sed -e 's/ //g' | sed -e 's/+/ + /g' | sed -e 's/x/ x /g') = $(($(echo "$*" | sed -e 's/ //g' | sed -e 's/\(\|[^x+]*\)/(\1)/g' | sed -e 's/|/1 + /g' | sed -e 's/ + $//g' | sed -e 's/ + +/ + /g' | sed -e 's/ + x/ \* /g' | sed -e 's/ + \([^1]\)/\1/g' | sed -e 's/x/ \* /g'))) ($(($(echo "$*" | sed -e 's/ //g' | sed -e 's/|/1 p /g' | sed -e 's/ p $//g' | sed -e 's/x/2 p /g' | sed -e 's/+/2 p /g' | sed -e 's/p/+/g'))) tandenstokers)"