Home > Software engineering >  using glob to substitute a variable
using glob to substitute a variable

Time:05-10

After reading some docs from globs in bash

https://mywiki.wooledge.org/glob#extglob

I´m struggling to replace a part of a variable:

Just an example that i am using to learn a bit more

myvar="value1=aaa value2=bbb value3=ccc value4=ddd"

value2="zzz"

myvar="${myvar//value2=*([a-z0-9-])/value2=${value2}}"

result:

echo $myvar
value1=aaa value2=zzz

expected result:

echo $myvar
value1=aaa value2=zzz value3=ccc value4=ddd

The result of the code above is not the expected one as it´s deleting everything behind value2=bbb in myvar.

If I use:

shopt -s extglob

it is working from a virtual machine with linux but from my current machine is not even if the begining of the script starts with #!/bin/bash. Most probably because i´m not using bash in my terminal.

Any other way to achieve this? (with sed for example without enabling extglob)

thx

CodePudding user response:

If you really can't use Bash, then you can maybe do what you want with lowest common denominator shell features like this:

pre=${myvar%%value2=*}
post=${myvar#"$pre"value2=}
v2=${post%%[!a-z0-9-]*}
post=${post#"$v2"}
myvar="${pre}value2=${value2}${post}"
  • Related