How to merge files in bash in alphabetical order

javanix picture javanix · Aug 24, 2011 · Viewed 9.4k times · Source

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?

Answer

Shawn Chin picture Shawn Chin · Aug 24, 2011

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?"