bash中“$ {file%。*}”的含义是什么

问题描述 投票:0回答:2

我正在读Using bash, how can I remove the extensions of all files in a specific directory?。接受的答案是:

for file in "$path"/*; do
    [ -f "$file" ] || continue
    mv "$file" "${file%.*}"
done

我不明白这条线:

    mv "$file" "${file%.*}"

尽管阅读了http://mywiki.wooledge.org/BashGuide/Patterns等一些资源

这里发生了什么?

bash git-bash
2个回答
0
投票

这是Parameter Expansion的一种形式。

"${file%.*}"的意思是“变量file减去包括最右边时期之后的所有内容。” ${file%%.*}"将参考最左边的时期。

这是${%}算子和Glob的组合。

编辑:我很难用这个“子串删除”扩展,直到我注意到#$的“左”,而%是右边。参数扩展是使用Bash作为脚本语言的基本要素;我建议练习。


1
投票

查看parameter substitution的文档

${var%Pattern}, ${var%%Pattern}

${var%Pattern}$var移除$Pattern最短的部分,与$var的后端相匹配。

${var%%Pattern}$var移除$Pattern最长的部分,与$var的后端相匹配。

它基本上是用完整的文件名填充$file,然后删除%之后的所有内容,.*的最短匹配,这将是任何扩展名。

# assume you want to convert myfile.txt to myfile
$file="myfile.txt"
# move the current name to the current name excluding the shortest match of .* = .txt
mv "$file" "${file%.*}"
# expands to
mv "myfile.txt" "myfile"
© www.soinside.com 2019 - 2024. All rights reserved.