bash 中的“${file%.*}”是什么意思

What does "${file%.*}" mean in bash

我正在通读 。接受的答案是:

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

我不明白这行:

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

尽管阅读了许多资源,例如 http://mywiki.wooledge.org/BashGuide/Patterns

这里发生了什么?

这是 Parameter Expansion 的一种形式。

"${file%.*}" 表示 "Variable file minus everything after and including the right-most period." ${file%%.*}" 将引用 最左边的 句点。

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

编辑:我在这个 "substring removal" 扩展上遇到了困难,直到我注意到 #$ 的 'left',而 %在右边。参数扩展是使用 Bash 作为脚本语言的基本要素;我建议练习。

查看 parameter substitution

的文档

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

${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.

${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $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"