'Sed replacement in bash [duplicate]

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?



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pjh