根据man bash
:
${parameter#word} ${parameter##word} Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching below. If the pattern matches the beginning of the 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}
。
我正在寻找能够说明两种语法之间不同行为的情况。顺便说一句,什么是最短匹配模式以及什么是最长匹配模式?
答案1
这个例子可能更能说明问题
$ parameter="This is a sentence with many words. Some of the words appear more than once. Oh, my word!"
$ echo "${parameter#*word}"
s. Some of the words appear more than once. Oh, my word!
$ echo "${parameter##*word}"
!
所以:
${parameter#pattern}
删除最短模式的匹配${parameter##pattern}
删除最长模式的匹配
还有${parameter%pattern}
和${parameter%pattern}
与 处的模式相匹配结尾字符串的。我记得差异是因为#看起来前 %在(美国)键盘上。
答案2
我刚刚找到这个例子:
$ INT=00011
$ echo "${INT#*0}"
0011
$ echo "${INT##*0}"
11
这里,我们首先将字符串“00011”赋给变量“INT”,然后输出以“INT”为参数、“*0”为字模式的${parameter#word}
or进行参数扩展的结果。${parameter##word}
这最小[前缀]匹配'*0' 的参数只是 '0',而最大[前缀]匹配是“000”。