I need a bash script for flattening a directory with same names, and get an ordered output after a conversion.

input folder structure:




and I need an output directory like this:


where /out/file004.mp3 is the mp3 conversion of /in2/file1.wav

I've done some trials with find -exec but I can't get it to work

(don't worry about conversion, I just use ffmpeg -i fileinput fileoutput.mp3)

  • You need leading zeros? – thefourtheye May 5 '13 at 12:42
  • yes, i absolutly need them! – nkint May 5 '13 at 13:05

ok, i understand that shell scripting is a really power tool but it is real mess:

i have tried with thefourtheye answer but the sort command messed everything up because of the order was like this:

Sequence 1.wav
Sequence 10.wav
Sequence 11.wav
Sequence 12.wav
Sequence 2.wav
Sequence 3.wav
Sequence 4.wav

and the spaces was a problem so i had to add " but there was some mess too i don't remember exactly where, then i tried to put some debug print and it didn't work so... In the end I tested it on a Mac OS/X terminal and it has another shell i never heard about (zsh) that uses different commands.. a big mess.

I came up with a small python script. Maybe it is dirty but it works:

import os, sys

count = 1
for dirpath, diname, filenames in os.walk('.'):

    if dirpath=='.' or dirpath=='./out':

    filenames = [f for f in filenames if f.split('.')[1]=='aif' and f[0]!='.']
    filenames = sorted(filenames, key=lambda f: int(f.split('.')[0].split(' ')[1]))

    for f in filenames:
        filepath = dirpath+'/'+f
        ffmpeg_command = 'ffmpeg -i "'+filepath+'" out/track'+"%04d" % (count,)+'.mp3'
        count += 1
        print ffmpeg_command
| improve this answer | |

Here's roughly how I would do it. Iterate the directories in the right order, then the files. It assumes there's no dir higher than in9/ and no file higher than file99.wav . If there are, extend the loops accordingly. E.g. for dir in in[0-9]/ in[1-9][0-9]/; do

for dir in in[0-9]/; do
    for file in "$dir"/file[0-9].wav "$dir"/file[1-9][0-9].wav; do
        printf -v dest 'out/file%04d.mp3' "$((++i))"
        ffmpeg -i "$file" "$dest"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.