bash for循环中没有扩展名的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7119223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:55:33  来源:igfitidea点击:

File name without extension in bash for loop

bash

提问by Bogdan Balan

In a for loop like this one:

在这样的 for 循环中:

for f in `ls *.avi`; do echo $f; ffmpeg -i $f $f.mp3; done

$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?

$f 将是完整的文件名,包括扩展名。例如,对于song1.avi,命令的输出将是song1.avi.mp3。有没有办法只获取song1,而没有for循环中的.avi?

I imagine there are ways to do that using awk or other such tools, but I'm hoping there's something more straight forward.

我想有一些方法可以使用 awk 或其他此类工具来做到这一点,但我希望有更直接的方法。

Thanks

谢谢

回答by Mu Qiao

Use bash parameter expansion

使用 bash 参数扩展

${f%%.*}

Note that you need the greedy version because there are multiple dots in the file name.

请注意,您需要贪婪版本,因为文件名中有多个点。

From bash manual:

从 bash 手册:

${parameter%word}

${parameter%%word}

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.

${参数%word}

${参数%%word}

这个词被扩展以产生一个模式,就像在文件名扩展中一样。如果模式匹配参数扩展值的尾部部分,则扩展的结果是具有最短匹配模式('%' 大小写)或最长匹配模式('%%' 大小写)的参数值删除。如果参数为'@'或' ',则模式移除操作依次应用于每个位置参数,扩展为结果列表。如果参数是一个带有'@'或'''下标的数组变量,则对数组的每个成员依次应用模式移除操作,扩展为结果列表。

回答by spsuaiken

This should do it:

这应该这样做:

for i in *.m4a; do
  ffmpeg -i $i ${i%%.*}.mp3
done