Sathish Kumar Sathish Kumar - 2 months ago 7
Bash Question

What does ## and % mean in shell?

We had to get the 'filename' and 'file extension' from a string

[sathish@oc Desktop]$ export FILE="filename.txt"


The following syntax works fine. However, we would like to understand how '##.' and '%.' works

[sathish@oc Desktop]$ echo ${FILE##*.}
txt
[sathish@oc Desktop]$ echo ${FILE%.*}
filename


Any help would be nice

Answer

Your starting point would be to read the bash manual, especially the section on Shell Parameter Expansion.

Some relevant excerpts:

${parameter#word}
${parameter##word}

The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Comments