语法“${foo##*.}”如何获取文件扩展名?

xia*_*012 9 shell-script

为什么此命令可以成功检索文件扩展名?

file_ext=${filename##*.}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 12

这在POSIX Shell 命令语言中进行了描述:

${parameter##word}
Run Code Online (Sandbox Code Playgroud)

删除最大的前缀模式。这个词应该被扩展以产生一个模式。然后参数扩展将导致参数,其中与删除模式匹配的前缀的最大部分。

在这种特定情况下,*.扩展为以.(*匹配任何内容)结尾的最大子字符串,并删除该最大子字符串。所以只剩下文件扩展名。

请注意,如果文件名不包含.,则不会删除任何内容,因此在脚本中使用它时要小心,行为可能不是您所期望的。


mic*_*has 9

看看man bash(或您正在使用的任何外壳):

   ${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.
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,它会删除最后一个“.”之前的所有内容。并返回剩余的字符串,它恰好是文件的扩展名。