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?
val21would match this -- it's zero spaces on both sides, after all! I'm presuming that what you're actually interested in is "space-or-beginning + 'val2' + space-or-end".unset arr["val2"]; for an ordered list you could do the same by index. String-munging in bash to maintain a list tends to be a code smell in and of itself, as it typically indicates poor choice of data structures.