So I have an exercise in which I need to calculate a certain string.
For example the string "|| x ||| + ||". The vertical lines represent a 1. So the solution to this string needs to be 8. So I made this script:
#!/bin/bash
result=$(echo $1 | tr -d ' ' | sed 's/|/1+/g' | sed 's/++/+/g' | sed 's/+x/x/g' | sed 's/ sed 's/x/*/g' | sed 's/+$//' | sed 's/$/\n/' | bc)
But when I executed this script on the string example, the solution I got was 6. Then I figured out it's because the script executes this: 1+1*1+1+1+1+1. So I need a way to make parenthesis between (1+1)*(1+1+1)+(1+1) but I can't figure it out.
Can anybody help me? Thanks in advance!
If you want to stick to sed then the best is to put in the parens before doing the rest:
result=$(echo $1 | tr -d ' ' | sed -e 's/\(|*\)/(\1)/g' -e 's/|/1+/g' -e 's/+)/)/g' -e 's/x/*/g' | bc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With