简体   繁体   English

如何在Linux Shell脚本中更改文件扩展名?

[英]How to change file extension in Linux shell script?

I've found some examples of doing this in similar situations, but this is the only shell-script I've written that does anything besides run commands verbatim, so I am struggling to apply the examples to my own situation and need some hand-holding <3 我已经找到了在类似情况下执行此操作的一些示例,但这是我编写的唯一的脚本,除了逐字逐行运行命令外,它还可以执行其他任何操作,因此我正在努力将这些示例应用于自己的情况,并且需要一些手工操作保持<3

I'm just trying to batch rip audio from MP4s. 我只是想从MP4批处理翻录音频。 This script works: 该脚本有效:

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

But the files all end with .mp4.mp3. 但是文件都以.mp4.mp3结尾。 How can I get rid of the mp4 part? 我如何摆脱mp4部分?

If you're using bash 如果您正在使用bash

${f%%.mp4}

will give the filename without the .mp4 extension. 将提供不带.mp4扩展名的文件名。

Try using it like this: 尝试像这样使用它:

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

... and don't forget the do keyword as in the example given. ...并且不要忘记给定示例中的do关键字。

Explanation 说明

The bash Manual( man bash ) states: bash手册( man bash )指出:

${parameter%word} ${parameter%%word} $ {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. 如果该模式与参数的扩展值的尾部部分匹配,则扩展的结果是具有最短匹配模式( %'' case) or the longest matching pattern (the %%''情况的参数的扩展值)已删除。 If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. 如果parameter为@或*,则将模式去除操作依次应用于每个位置参数,并且扩展为结果列表。 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. 如果parameter是用@或*下标的数组变量,则将模式删除操作依次应用于数组的每个成员,并且扩展为结果列表。

This is just one of many string manipulations you can perform on shell variables. 这只是可以对shell变量执行的许多字符串操作之一。 They all go by the name of Parameter Expansion . 它们都以Parameter Expansion的名称命名。

That's as well the section label given in the bash manual. 这也是bash手册中给出的部分标签。 Thus man bash /paramter exp should bring you there fast. 因此, man bash / paramter exp应该可以带您快速到达那里。 ` `

以下命令更改当前目录下所有文件的文件扩展名。

find . -depth -name "*.c" -exec sh -c 'dname=$(dirname {}) && fname=$(basename {} .c) && mv {} $dname/$fname.h' ";"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM