Home > Enterprise >  sed - regexp - adding rounded parenthesis on a mathematical expression
sed - regexp - adding rounded parenthesis on a mathematical expression

Time:01-09

I'm trying to write a sed command with a regex with the purpose to add rounded parenthesis around numbers to be added.

In particular, considering this expression example 86 * 21 7 * 13 * 31 26 31 * 5 I would like to have a result as 86 * (21 7) * 13 * (31 26 31) * 5.

I created the following sed command: sed -e 's/\([0-9]\ .[0-9]\ \)/(\1)/g' expr.txt but I'm able only to set rounder parenthesis each 2 numbers and not more, like 86 * (21 7) * 13 * (31 26) 31 * 5.

I also tried to use sed -e 's/\([0-9]\ .*[^\*].*[0-9]\ [^ \*]\)/(\1)/g' (specifically `[^*] in order to exclude the multiplication) with no luck.

How can I reach to have a result that is able to set rounded parenthesis for all concatenated addition operations like 86 * (21 7) * 13 * (31 26 31) * 5?

How to manage particular cases like:

  • 23 (2 * 53) (34 * 66) * 55 that should produce ((23 (2 * 53)) (34 * 66)) * 55

CodePudding user response:

Try

sed 's/\([0-9]\ \(   [0-9]\ \)\ \)/(\1)/g'

Personally, I prefer the -E style where () and are operators by default and have to be escaped to denote literals:

sed -E 's/([0-9] ( \  [0-9] ) )/(\1)/g'
  • Related