How to merge files in bash in alphabetical order

前端 未结 2 1748
借酒劲吻你
借酒劲吻你 2021-02-09 03:35

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

相关标签:
2条回答
  • 2021-02-09 03:52

    try:

    ls | sort | xargs cat > merged.mp3
    

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

    0 讨论(0)
  • 2021-02-09 03:56

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

    0 讨论(0)
提交回复
热议问题