为什么此命令可以成功检索文件扩展名?
file_ext=${filename##*.}
答案1
${parameter##word}
删除最大前缀模式。该词应扩展以产生一种模式。然后,参数扩展应产生参数,其中前缀的最大部分与删除的模式匹配。
在这种特定情况下,*.
被扩展为以.
(*
匹配任何内容) 结尾的最大子字符串,并且该最大子字符串被删除。所以只剩下文件扩展名了。
请注意,如果文件名不包含 ,则不会删除任何内容.
,因此在脚本中使用它时要小心,行为可能不是您所期望的。
答案2
看看man bash
(或者你正在使用的任何 shell):
${parameter##word}
Remove matching prefix pattern. The word is expanded to produce
a pattern just as in pathname expansion. 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 pat‐
tern (the ``##'' case) deleted. If parameter is @ or *, the
pattern removal operation is applied to each positional parame‐
ter in turn, and the expansion is the resultant list. If param‐
eter 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.
因此,在您的情况下,它会删除最后一个“.”之前的所有内容。并返回剩余的字符串,该字符串恰好是文件的扩展名。