linux - shell 参数名称后带有井号和百分号的语法

标签 linux bash shell

<分区>

请解释以下语法:

  i##*.

  i%.*   

我明白它在做什么,但我想知道一般模式(它为什么/如何这样做)。

出现的代码:

#!/bin/bash

recursive_name_change()
{
    cd "$1"
    for i in *
    do
        #echo "${i##*.}"
        if [ -d "$i" ]
        then
            recursive_name_change "$i"
        elif [ "${i##*.}" = "cpp" ]
        then
             new_name=${i%.*}".c"
        mv "$i" "$new_name"
        fi
        done
        cd ../
    }

recursive_name_change .

还请大神指点,这些奇特的语法形式从哪里找?

最佳答案

请参阅 man bash 中的参数扩展:

   ${parameter#word}
   ${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 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}

Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion 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. 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 mem- ber of the array in turn, and the expansion is the resultant list.

简而言之,#去掉左边的模式,%去掉右边的模式,加倍符号使匹配变得贪婪。 (助记:# 在大多数键盘上位于 % 的左侧)。

关于linux - shell 参数名称后带有井号和百分号的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36036561/

相关文章:

linux - 在 bash 中遍历数组时获取变量名

bash - sed:在文件最后一行的位置搜索和替换值

linux - 创建路径名来检查文件不存在/权限被拒绝错误

ANDROID_HOME 未应用

c - mlockall 和共享库

linux - 如何从网站上获取所有热链接图像?

bash - 如何在运行java -jar命令时获取unix进程ID

bash - 执行 bash 然后在 docker 中运行命令

node.js - 为什么在 env 调用中将参数传递给命令不起作用?

c - C 中的 Fork() 程序