Novice C Novice C - 3 months ago 13
Bash Question

Shell string manipulation, wildcard scope

I am attempting to manipulate a string in shell by removing a substring, separated by some delimiters. Currently I am having some undesired behavior from the wildcard character as follows:

string='start.badstuff.goodstuff.end'
echo ${string/bad*.} #start.end


In the above example say I know the substring I seek to remove starts with
'bad'
followed by random
'stuff.'
all of which I wish to remove. I want to keep the string
'goodstuff'
, however, in this example the wildcard takes the widest scope instead of the narrowest (taking
*='stuff.goodstuff'
instead of the desired behavoir
*='stuff'
).

Is there a way to limit the scope of the wildcard to stop at the first
'.'
after
'badstuff'
, without knowing what
'goodstuff'
might be?

Answer

With enabled ext. glob (see on this page for details)

shopt -s extglob

you could do

echo ${string/bad*([^.]).}

which results in

start.goodstuff.end