bash for loop中没有扩展名的文件名 [英] File name without extension in bash for loop
问题描述
在这样的for循环中:
In a for loop like this one:
for f in `ls *.avi`; do echo $f; ffmpeg -i $f $f.mp3; done
$ f将是完整的文件名,包括扩展名.例如,对于song1.avi,命令的输出将是song1.avi.mp3.有没有办法只获取song1,而没有for循环中的.avi?
$f will be the complete filename, including the extension. For example, for song1.avi the output of the command will be song1.avi.mp3. Is there a way to get only song1, without the .avi from the for loop?
我想有很多方法可以使用awk或其他类似的工具来做到这一点,但我希望还有一些更简单的方法.
I imagine there are ways to do that using awk or other such tools, but I'm hoping there's something more straight forward.
谢谢
推荐答案
使用bash参数扩展
${f%%.*}
请注意,您需要贪婪的版本,因为文件名中包含多个点.
Note that you need the greedy version because there are multiple dots in the file name.
来自bash手册:
$ {parameter%word}
$ {parameter %% word}
该单词被扩展以产生一个模式,就像文件名扩展一样.如果该模式与参数的扩展值的结尾部分匹配,则扩展的结果是具有最短匹配模式(%"情况)或最长匹配模式("%%"情况)的参数值已删除.如果参数是"@"或"",则模式去除操作将依次应用于每个位置参数,并且扩展名是结果列表.如果parameter是下标为'@'或''的数组变量,则将模式删除操作依次应用于数组的每个成员,并且扩展为结果列表.
The word is expanded to produce a pattern just as in filename expansion. 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. 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.
这篇关于bash for loop中没有扩展名的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!