Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sed replacement in bash

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading