Reputation: 155
I have searched a lot, and while I see a couple of examples of these used, specifically from here:
scale=${scale##*[!0-9]*}
[ -z "${scale//[0-9]}" ]
There is no explanation for what these symbols do, how they work or when to use them scripting. I have not found them explained elsewhere when special symbols are discussed. Looks like they could be useful. Can anyone explain how the ##
and //
work in the script examples on the page linked above? Thanks.
Upvotes: 1
Views: 107
Reputation: 780724
They're part of shell parameter expansion syntax, used to modify the value of the variable. #
and %
are used to delete a prefix or suffix of the variable, and //
is used to substitute one string for another.
${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.
So ${scale##*[!0-9]*}
means to remove the beginning of the string that matches anything followed by a non-digit followed by anything. So foobar
becomes an empty string (because everything is removed), while 123
is left alone because [!0-9]
never matches anything.
${parameter/pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with ‘/’, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with ‘#’, it must match at the beginning of the expanded value of parameter. If pattern begins with ‘%’, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted.
So ${scale//[0-9]}
simply removes all digits from the the value of the variable, then test -z
is used to test if this is an empty string (meaning the original string only had digits).
Upvotes: 5
Reputation: 2691
From: http://tldp.org/LDP/abs/html/string-manipulation.html
${string##substring}
Deletes longest match of $substring from front of $string.
${string//substring/replacement}
Replace all matches of $substring with $replacement.
Upvotes: 1