如何在bash中匹配字符串中的后缀?

如何在bash中匹配字符串中的后缀?,bash,pattern-matching,Bash,Pattern Matching,我想检查输入参数是否以“.c”结尾?我怎么检查?以下是我到目前为止得到的(感谢您的帮助): 案例的经典案例 case $i in *.c) echo Yes;; esac 是的,语法很难懂,但你很快就会习惯。与各种Bash和POSIX扩展不同,它可以一直移植到原始的bourneshell for i in $@; do if [ -z ${i##*.c} ]; then echo "YES: $i" fi done $ ./test.sh .c .c-and

我想检查输入参数是否以“.c”结尾?我怎么检查?以下是我到目前为止得到的(感谢您的帮助):


案例的经典案例

case $i in *.c) echo Yes;; esac
是的,语法很难懂,但你很快就会习惯。与各种Bash和POSIX扩展不同,它可以一直移植到原始的bourneshell

for i in $@; do
    if [ -z ${i##*.c} ]; then
        echo "YES: $i"
    fi
done


$ ./test.sh .c .c-and-more before.c-and-after foo.h foo.c barc foo.C
YES: .c
YES: foo.c
$
解释(感谢):

  • 迭代命令行参数:$@中i的
    ;执行
  • 主要技巧是:
    if[-z${i###*.c}];然后
    。这里我们检查字符串
    ${i###*.c}
    的长度是否为零
    ${i##*.c}
    的意思是:获取$i值并通过模板“*.c”删除子字符串。若结果是空字符串,那个么我们有“.c”后缀
  • 这里如果有来自man bash的一些附加信息,请参阅节参数Expasion

    ${parameter#word}
    ${parameter##word}
        Remove matching prefix pattern.  The word is expanded to produce a pat‐
        tern just as in pathname expansion.  If the pattern matches the  begin‐
        ning 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.
    

    我想foo.c应该换成$I?对。不需要引号,因为
    [[
    知道该做什么,而不像
    [
    “当使用“==”和“!=”运算符时,运算符右侧的字符串被视为一个模式,并根据模式匹配中描述的规则进行匹配。”-请解释你的代码。试着从初学者的角度来看。不需要解释就可以理解的人可以自己编写代码。例如,值得解释
    #
    操作符的名称(以便OP可以搜索更多文档),并记录
    #
    #
    之间的区别。jpaugh,我已经添加了解释。谢谢。谢谢!我期待着看到您将来对SO网站和社区的贡献。
    for i in $@; do
        if [ -z ${i##*.c} ]; then
            echo "YES: $i"
        fi
    done
    
    
    $ ./test.sh .c .c-and-more before.c-and-after foo.h foo.c barc foo.C
    YES: .c
    YES: foo.c
    $
    
    ${parameter#word}
    ${parameter##word}
        Remove matching prefix pattern.  The word is expanded to produce a pat‐
        tern just as in pathname expansion.  If the pattern matches the  begin‐
        ning 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.