How to merge files in bash in alphabetical order

允我心安 提交于 2020-01-12 05:23:07

问题


I need to merge a bunch of mp3 files together. I know that simply doing

cat file1.mp3 >> file2.mp3

seems to work fine (at least it plays back correctly on my Zune anyway).

I'd like to run

cat *.mp3 > merged.mp3

but since there are around 50 separate mp3 files I don't want to be surprised halfway through by a file in the wrong spot (this is an audio book that I don't feel like re-ripping).

I read through the cat man pages and couldn't find if the order of the wildcard operator is defined.

If cat doesn't work for this, is there a simple way (perhaps using ls and xargs) that might be able to do this for me?


回答1:


Your version (cat *.mp3 > merged.mp3) should work as you'd expect. The *.mp3 is expanded by the shell and will be in alphabetical order.

From the Bash Reference Manual:

After word splitting, unless the -f option has been set, Bash scans each word for the characters ‘*’, ‘?’, and ‘[’. If one of these characters appears, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of file names matching the pattern.

However, do be aware that if you have many files (or long file names) you'll be hampered by the "argument list too long" error.

If that happens, use find instead:

find . -name "*.mp3" -maxdepth 0 -print0 | sort -z | xargs -0 cat > merged.mp3

The -print0 option in find uses a null character as field separators (to properly handle filenames with spaces, as is common with MP3 files), while the -z in sort and -0 in xargs informs the programs of the alternative separator.

Bonus feature: leave out -maxdepth 0 to also include files in sub directories.


However, that method of merging MP3 files would mess up information such as your ID3 headers and duration info. That will affect playability on more picky players such as iTunes (maybe?).

To do it properly, see "A better way to losslessly join MP3 files" or " What is the best way to merge mp3 files?"




回答2:


try:

ls | sort | xargs cat > merged.mp3

(Anyway I'm not sure that you can merge mp3 files that way)



来源:https://stackoverflow.com/questions/7176572/how-to-merge-files-in-bash-in-alphabetical-order

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