knokej
knokej

Reputation: 71

trouble doing parameter prefix or suffix removal with extglob

I am trying to essentially pull a regex substring out of the middle of a superstring directly in a bash script, without fork/execing to grep (or something). To do this, I wanted to use shell parameter expansion to remove the unwanted prefix and then unwanted suffix from the superstring. But the prefix and suffix are near regular expression too, so I was trying to enable extglob and do the something like (under Cygwin):

$ echo $BASH_VERSION
4.1.10(4)-release
$ shopt -s extglob
$ foo=foobar
$ echo $foo
foobar
$ echo ${foo#fo}   #simple prefix removal works as expected
obar
$ echo ${foo/!(FO)/SUB}   #substitution using extglob works
SUB
$ echo ${foo#!(FO)}
foobar
$ echo ${foo##!(FO)}
<nothing>
$ echo ${foo%ar}   #simple suffix removal works as expected
foob
$ echo ${foo%!(AR)}
foobar
$ echo ${foo%%!(AR)}
<nothing>

Can anyone explain the results of prefix and suffix removal when the extglob ! syntax is used? Is it a bash bug? (If I could figure this out, then I would be trying more complicated patterns than "FO" and "AR".)

Upvotes: 0

Views: 106

Answers (2)

choroba
choroba

Reputation: 241918

${foo%!(AR)} means "Remove the shortest suffix that is not AR". The shortest such suffix is the empty string.

${foo%%!(AR)} means "Remove the longest suffix that is not AR". In case of "foobar", it removes everything. To get some more interesting results, try:

$ echo ${foo%%!(foobar)}
f
$ echo ${foo%%!(*bar)}
foob

Upvotes: 1

chepner
chepner

Reputation: 531315

%% removes the longest matching suffix. Since foobar is the longest prefix that matches "not AR", the entire string is removed.

Upvotes: 0

Related Questions