linux - 如何在 Linux shell 脚本中更改文件扩展名?

标签 linux shell

我已经找到了一些在类似情况下执行此操作的示例,但这是我编写的唯一一个除了逐字运行命令之外还执行任何操作的 shell 脚本,因此我很难将这些示例应用到我自己的情况和需要一些手握<3

我只是想从 MP4 中批量翻录音频。这个脚本有效:

for f in *.mp4; 
    ffmpeg -i "$f" -f mp3 -ab 192000 -vn "mp3s/$f.mp3"
done

但是文件都是以.mp4.mp3结尾的。我怎样才能去掉 mp4 部分?

最佳答案

如果你正在使用 bash

${f%%.mp4}

将给出不带 .mp4 扩展名的文件名。

尝试像这样使用它:

for f in *.mp4; do
    ffmpeg -i "$f" -f mp3 -ab 192000 -vn "mp3s/${f%%.mp4}.mp3"
done

...并且不要像给定的示例那样忘记 do 关键字。

解释

bash 手册(man bash) 指出:

${parameter%word} ${parameter%%word}

Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded 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.

这只是您可以对 shell 变量执行的众多字符串操作之一。它们都被称为参数扩展

这也是 bash 手册中给出的部分标签。因此 man bash /paramter exp 应该会很快带你到那里。 `

关于linux - 如何在 Linux shell 脚本中更改文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15234593/

相关文章:

c - poll() 不阻塞,立即返回

Linux 线性到物理地址的映射

python - 处理不带双引号的 CSV 文件

python - Bash 命令仅在第一次执行

linux - 如何打印/tmp 目录中每个文件除最后 20 行之外的所有内容?

c - 进程如何知道它何时进入后台?

linux - 通过 bash 脚本从文本文件运行命令

linux - Apache 将 HTTPS 重定向到 HTTP

bash - Bash脚本中的Sudo SU无需询问用户密码

bash - 我该如何改进这个脚本?