Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply in bash script according to mathrules

Tags:

bash

shell

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!

like image 602
Dries Coppens Avatar asked Dec 15 '22 10:12

Dries Coppens


1 Answers

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)
like image 77
LaszloLadanyi Avatar answered Dec 26 '22 10:12

LaszloLadanyi