0

sed keeps giving invalid arithmetic operator error. I am trying to assign the output of sed to a variable.

This one works,

var=$(sed  -e 's/"currentGeneration":5010/"currentGeneration":5011/'  <<< $content )

but when I try to do the same with variable instead of 5010 and 5011, it fails with invalid arithmetic operator

var=$((sed  -e 's/"currentGeneration":$currg/"currentGeneration":$nextg/'  <<< $content ))

I tried below also but it won't substitute anything.

var=$(sed  -e 's/"currentGeneration":$currg/"currentGeneration":$nextg/'  <<< $content )

I am pretty sure I am missing something basic. Learning shell scripting on the job :(

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
Ram
  • 25
  • 4
  • Check your quoting – sseLtaH Sep 27 '21 at 15:09
  • 2
    `$( ... )` is command substitution, `$(( ... ))` is arithmetic expansion. (If you're running that on an interactive Bash, the error message should begin with `bash: ...`, implying it's from Bash and not sed.) I can't tell any reason why the parentheses would have been doubled there. The other issue is with double quotes `""` vs. single quotes `''`, see [What is the difference between the "...", '...', $'...', and $"..." quotes in the shell?](https://unix.stackexchange.com/questions/503013/what-is-the-difference-between-the-and-quotes-in-th) – ilkkachu Sep 27 '21 at 15:18
  • Copy/paste that and any other shell scripts you write into http://shellcheck.net and fix the issues that tool can tell you about. – Ed Morton Sep 28 '21 at 22:20

1 Answers1

3

In you command

var=$(sed  -e 's/"currentGeneration":$currg/"currentGeneration":$nextg/'  <<< $content )

$currg and $nextg are not expanded since they are not between double quotes.

To avoid the problem, you have a couple of options:

  • Use sed surrounded by double quotes and escape the inner double quotes:

    $ var=$(sed  -e "s/\"currentGeneration\":$currg/\"currentGeneration\":$nextg/"  <<< "$content" )
    
  • Concatenate single quotes with double quotes:

    $ var=$(sed  -e 's/"currentGeneration":'"$currg"'/"currentGeneration":'"$nextg/"  <<< "$content" )
    

Note that $content should be enclosed in double quotes.

(( is a compound command to evaluate arithmetic operations, so it's not doing what you intend to.

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57