How to combine files in bash in alphabetical order

I need to combine a bunch of mp3 files. I know what to just do

cat file1.mp3 >> file2.mp3 

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

I want to run

 cat *.mp3 > merged.mp3 

but since there are about 50 separate mp3 files, I don’t want to be surprised by half the file in the wrong place (this is an audio book that I don’t feel like copying again).

I read the cat’s character pages and couldn’t find if the template’s action order was set.

If cat doesn't work for this, is there an easy way (maybe using ls and xargs ) that could do this for me?

+7
source share
2 answers

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

In the Bash Reference Guide :

After word splitting, if the -f option is not set, does Bash scan each word for the characters '*,'? and '[. If one of these characters appears, this word is considered as a pattern, and is replaced by an alphabetically sorted list of file names matching the pattern.

However, keep in mind that if you have many files (or long file names), it will be too difficult for you to keep a list of arguments. "

If this happens, use find instead:

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

The -print0 parameter in find uses the null character as field delimiters (to properly handle file names with spaces, as is usually the case with MP3 files), and -z in sort and -0 in xargs tells alternate delimiter programs.

Bonus feature: leave -maxdepth 0 to include files in subdirectories.


However, this method of merging MP3 files can ruin information such as ID3 headers and duration information. This will affect the playability of more attractive players like iTunes (maybe?).

To do this correctly, see "The Best Lossless Way to Join MP3 Files " or " What is the Best Way to Merge MP3 Files? "

+12
source

to try:

 ls | sort | xargs cat > merged.mp3 

(Anyway, I'm not sure if you can combine mp3 files this way)

+3
source

All Articles