Hi,
I am a shell script newbie. I want to know the difference between
${var%pattern}
and
${var%%pattern}
Thanks
Hi,
I am a shell script newbie. I want to know the difference between
${var%pattern}
and
${var%%pattern}
Thanks
From man bash
:
${parameter%word} ${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion 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.
From man bash
:
${parameter%word} ${parameter%%word}
The
word
is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value ofparameter
, then the result of the expansion is the expanded value ofparameter
with the shortest matching pattern (the "%" case) or the longest matching pattern (the "%%" case) deleted.
Here's an example of what the difference is:
$ VAR=abcdefabcdef
$ echo ${VAR%def*}
abcdefabc
$ echo ${VAR%%def*}
abc
Notice that there are two possible matches for def*
at the end of $VAR
: both "defabcdef" and just "def" match. With the "%" the shortest possible match for the pattern def*
is deleted, so the trailing "def" is removed. With the "%%" the longest possible match is deleted, so "defabcdef" bites the dust.
http://bash-hackers.org/wiki/doku.php/syntax/pe#substring_removal
Stackoverflow is no full replacement for a web search engine, just use both! ;-)