0

I´m wondering how can i just replace this variable easily in BASH:

VARIABLE1="VALUE2=somestring2 VALUE3=TRUE"

I need just to change VALUE2=somestring2 (which is just part of the string) with a new value that replaces it:

i am just using this:

VARIABLE1="${VARIABLE1//VALUE2=[a-z0-9-]*/}VALUE2=${VALUE2}"

where VALUE2=${VALUE2} is a new value that i specify in some line.

but there are two problems here:

1- the line where i overwrite the VALUE2=somestring2 deletes VALUE3=TRUE from VARIABLE1

2- looks like after overwrite VALUE2, it puts a "space" at the beginning of "VALUE2=somestring2"

echo $VARIABLE1 " VALUE2=somestring2"

Any way to fix this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
X T
  • 445
  • 6
  • 22
  • 2
    It is not a regex that you are using, it is a glob. That is why `*` grabs all text to the end. And you are not using sed here. – Wiktor Stribiżew May 09 '22 at 09:49
  • thanks for that. I see that * is messing what i want to do. But i did not find any way to fix it. – X T May 09 '22 at 09:50

1 Answers1

1

Try

shopt -s extglob
VARIABLE1=${VARIABLE1/VALUE2=*([a-z0-9-])/VALUE2=$VALUE2}
  • shopt -s extglob turns on extended globbing in Bash. That enables (among other things) the built-in substitution mechanism to use a form of regular expressions (*([a-z0-9-]) here). See the extglob section in glob - Greg's Wiki
  • Note that ALL_UPPERCASE variable names like VARIABLE1 are potentially dangerous. They can clash with the many special ALL_UPPERCASE variables that exist. See Correct Bash and shell script variable capitalization. Names like variable1 are generally safe.
pjh
  • 6,388
  • 2
  • 16
  • 17