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++ - 如何编写一个 C++ 例程来检查我按下了键盘上的哪个键,以便我可以单独处理每个按键?

linux - Linux内核空间中的进程

linux - "while (sleep 100 &!) do; done"在 zsh 中如何工作,它如何在 bash 中复制?

linux - 查找和删除具有非ASCII名称的文件

c++ - 如何在 Ubuntu 20.04 上安装 libstdc++6 调试符号?

linux - 需要增加HTTP并发连接数到85000

python - 等待 dbus session 锁定/解锁消息

linux - 我的远程服务器无法在 shell 脚本中使用 sftp 识别变量

linux - 我如何使用 GNU-utils 来过滤这样的文本?

unix - 如何从一行文本中选择给定的列?