${i%.*} 在这种情况下做什么?
What does ${i%.*} do in this context?
我正在学习 运行 bash 终端中的 bash 脚本,特别是在转换音频视频文件的上下文中。
我在 SO 上看到了这个命令,它完全符合我的要求。但是,我想更好地理解它:
for i in *.avi; do ffmpeg -i "$i" "${i%.*}.mp4"; done
现在,这显然是一个 for-loop
,我得到了第一个 *
通配符。我得到 do
块。但是我不太明白的是${i%.*}
。具体来说,%.*
位在输出位置有什么作用?为什么不使用 ${i}.mp4
呢?
它叫做 parameter expansion,它会删除从最后一个点(即扩展名)开始的所有内容。尝试以下操作:
$ i="foo.bar.baz"
$ echo ${i%.*}
foo.bar
原始代码的作者 ("${i%.*}.mp4"
) 显然想用 .mp4
替换原始扩展名,因此删除了原始扩展名并附加了 .mp4
。
参数展开
${参数%word}
${参数%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted.
我正在学习 运行 bash 终端中的 bash 脚本,特别是在转换音频视频文件的上下文中。
我在 SO 上看到了这个命令,它完全符合我的要求。但是,我想更好地理解它:
for i in *.avi; do ffmpeg -i "$i" "${i%.*}.mp4"; done
现在,这显然是一个 for-loop
,我得到了第一个 *
通配符。我得到 do
块。但是我不太明白的是${i%.*}
。具体来说,%.*
位在输出位置有什么作用?为什么不使用 ${i}.mp4
呢?
它叫做 parameter expansion,它会删除从最后一个点(即扩展名)开始的所有内容。尝试以下操作:
$ i="foo.bar.baz"
$ echo ${i%.*}
foo.bar
原始代码的作者 ("${i%.*}.mp4"
) 显然想用 .mp4
替换原始扩展名,因此删除了原始扩展名并附加了 .mp4
。
参数展开
${参数%word}
${参数%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted.