Given a string such as
string="val1 val2 val3 val4"
how can you use bash substring replacement to remove a given substring and its adjoining space (which may or may not be present)?
For example, this results in extra spaces:
val='val2'
string=${string/$val/}
# string = "val1 val3 val4"
In my real-life code, I won't know in advance what the substring is or where it resides in the string, so it will be unknown if it has leading or trailing spaces. I wanted to do something like this, like you'd do in sed
, but of course it didn't work:
val=" *val2 *"
string=${string/$val/ }
# In my fictitious universe, string = "val1 val3 val4"
# In the real world, string = "val1"
In sed
, I would use something like sed -e 's/ *val2 */ /'
, but I'd like to do all this from within bash.
Is there a way to define the substring such that the pattern contains zero-or-more spaces + 'val2' + zero-or-more spaces?