Change file extensions of multiple files in a directory with terminal/bash?

試著忘記壹切 提交于 2019-12-03 03:11:07

Try:

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

Or, if your shell has it:

rename .dat .mp3 *.dat

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.

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

and you typed:

mv *.dat *.mp3

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

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

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

t1.dat t2.dat

the command would have expanded to:

mv t1.dat t2.dat *.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.

For anyone on a mac, this is quite easy if you have BREW, if you don't have brew then my advice is get it. then when installed just simply do this

$ brew install rename

then once rename is installed just type (in the directory where the files are)

$ rename -s dat mp3 *
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!