使用terminal / bash更改目录中多个文件的文件扩展名? [英] Change file extensions of multiple files in a directory with terminal/bash?

查看:170
本文介绍了使用terminal / bash更改目录中多个文件的文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的launchdaemon,它将文件从一个目录复制到另一个目录。我已经把文件转移得很好了。

I'm developing a simple launchdaemon that copies files from one directory to another. I've gotten the files to transfer over fine.

我只是希望目录中的文件是.mp3而不是.dat的

I just want the files in the directory to be .mp3's instead of .dat's

部分文件如下所示:


6546785.8786.dat

3678685.9834.dat

4658679.4375.dat

6546785.8786.dat
3678685.9834.dat
4658679.4375.dat

我希望它们看起来像这样:

I want them to look like this:


6546785.8786.mp3

3678685.9834.mp3

4658679.4375.mp3

6546785.8786.mp3
3678685.9834.mp3
4658679.4375.mp3

这是我在bash脚本末尾重命名文件扩展名的内容。

This is what I have at the end of the bash script to rename the file extensions.

cd $mp3_dir
mv *.dat *.mp3
exit 0

问题是该文件是* .mp3而不是6546785.8786.mp3

Problem is the file comes out as *.mp3 instead of 6546785.8786.mp3

当另一个6546785.8786.dat文件导入$ mp3_dir时,* .mp3被覆盖新的.mp3

and when another 6546785.8786.dat file is imported to $mp3_dir, the *.mp3 is overwritten with the new .mp3

我需要将只是的.dat文件扩展名重命名为.mp3和保留文件名。

I need to rename just the .dat file extensions to .mp3 and keep the filename.

想法?建议?

推荐答案

尝试:

for file in *.dat; do mv "$file" "${file%dat}mp3"; done

或者,如果你的shell有它:

Or, if your shell has it:

rename .dat .mp3 *.dat

现在,为什么你的命令不起作用:首先,当你重命名为 * .mp3 时,你的目录中只有一个文件可以肯定,否则 mv 将失败 * .mp3:不是目录

Now, why your command didn't work: first of all, it is more than certain that you only had one file in your directory when it was renamed to *.mp3, otherwise mv would have failed with *.mp3: not a directory.

并且mv对文件globs没有任何魔力,它是扩展globs的 shell 。这意味着,如果你在目录中有这个文件:

And mv does NOT do any magic with file globs, it is the shell which expands globs. Which means, if you had this file in the directory:

t.dat

您键入:

mv *.dat *.mp3

shell将扩展 * .dat t.dat 。但是,因为没有任何东西可以匹配 * .mp3 ,shell会保持原样,这意味着完全展开的命令是:

the shell would have expanded *.dat to t.dat. However, as nothing would match *.mp3, the shell would have left it as is, meaning the fully expanded command is:

mv t.dat *.mp3

其中将创建一个名为 *。mp3 的文件。

Which will create a file named, literally, *.mp3.

如果,另一方面,你有几个文件名为 * .dat ,如:

If, on the other hand, you had several files named *.dat, as in:

t1.dat t2.dat

该命令将扩展为:

mv t1.dat t2.dat *.mp3

但这会失败:如果 mv 有两个以上的参数,它会预期最后一个参数(即 * .mp3 )是一个目录。

But this will fail: if there are more than two arguments to mv, it expects the last argument (ie, *.mp3) to be a directory.

这篇关于使用terminal / bash更改目录中多个文件的文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆