2

I want to remove ${} among arithmetic form in the file using sed for example abc=$(( ${var}+3 )) to abc=$(( var+3 ))

I'm using positional swapping in sed something like

sed -E 's/(\w+\W\$\(\( ) (\$\{) (\w+) (\}) (.*)/\1 \3 \5/g file.txt'

but it extracts only abc=3 when I use

echo abc=$((( ${var}+3 )) | sed -E 's/(\w+\W\$\(\( ) (\$\{) (\w+) (\}) (.*)/\1 \3 \5/' 

in terminal, just to check if it works all right

and it did nothing on shell script how can I remove only ${} part of the file?

I am using Mac OS and also tried on Ubuntu but it was still the same

2
  • 2
    Remark: you may need to discriminate keywords. $(( ${abc} + 12)) is, indeed $((abc + 12)). But $((${1}+1)) is not $((1+1)). Or, more convoluted example, $(({abc}0+12)) is not $((abc0+12)) (if abc=15 and abc0=20, first one is 162, second one is 32).
    – chrslg
    Commented Oct 7, 2022 at 13:40
  • So, all answer you'll get need some level on assumption on what is and is not in your code. Or must deal with some specific cases. From my examples, you get that the answer you got are not valid if $((...)) expression use positional arguments, or concatenation
    – chrslg
    Commented Oct 7, 2022 at 13:43

3 Answers 3

4

Using sed

$ sed -E 's/\$\{([^}]*)}/\1/' input_file
abc=$(( var+3 ))
1
  • It works perfectly fine, but I thought the result should be only \1 not everything but ${} can you explain why? I must have understood this concept completely wrong
    – mangs
    Commented Oct 11, 2022 at 11:38
3

1st solution: Using capturing groups concept here and substituting matched values with captured values and only with which are required please try following sed code. Here is the Online Demo for used regex in sed code.

s='abc=$(( ${var}+3 ))' ##shell variable
sed -E 's/^([^=]*=\$\(\( )\$\{([^}]*)}(.*)$/\1\2\3/' <<<"$s"

OR use following in case you have an Input_file from where you want to substitute values.

sed -E 's/^([^=]*=\$\(\( )\$\{([^}]*)}(.*)$/\1\2\3/' Input_file


2nd solution: Using Perl's one-liner approach using Lazy match regex to make life easier here, one could try following.

perl -pe 's/^(.*?)\$\{(.*?)\}(.*)$/$1$2$3/' Input_file
2
  • 1
    this works perfectly and I understood how it works, but one thing is that first ^, because the file I put in has 2 tabs in front of the string so I thought it shouldn't be detected, can you explain why?
    – mangs
    Commented Oct 11, 2022 at 11:33
  • @mangs, Sorry, could you please do explain it more what's not working and I could try to help you, cheers. Commented Oct 11, 2022 at 17:34
1
printf="abc=\$(( \${var}+3 )) to abc=\$(( var+3 ))" | tr -d '{' | tr -d '}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.