我正在读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等一些资源
这里发生了什么?
这是Parameter Expansion的一种形式。
"${file%.*}"
的意思是“变量file
减去包括最右边时期之后的所有内容。” ${file%%.*}"
将参考最左边的时期。
这是${%}
算子和Glob的组合。
编辑:我很难用这个“子串删除”扩展,直到我注意到#
是$
的“左”,而%
是右边。参数扩展是使用Bash作为脚本语言的基本要素;我建议练习。
${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"