Bash – extglob 2nd “zero or more” operator not working

bashshellvariable substitutionwildcards

Given:

$ shopt -s extglob
$ TEST="    z abcdefg";echo ">>${TEST#*( )z*( )}<<"
>> abcdefg<<

Why is there a space before the letter 'a'? I would expect that the 2nd *( ) would match the space, but it does not seams to do so.

I expected the equivalent of:

$ echo ">>$(echo -n "${TEST}" | perl -pe "s/^ *z *//g")<<"
>>abcdefg<<

The 2nd *( ) matches if I specify the next following character (which is 'a'):

$ shopt -s extglob
$ TEST="    z abcdefg";echo ">>${TEST#*( )z*( )a}<<"
>>bcdefg<<

Bash version: GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)

Best Answer

${TEST#...} matches the shortest string, which is z followed by zero spaces. You need ${TEST##...}, the longest match.

Related Question