1

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

input folder structure:

/in1/file1.wav
/in1/file2.wav
/in1/file3.wav

/in2/file1.wav
/in2/file2.wav
/in2/file3.wav
/in2/file4.wav

/in3/file1.wav
/in3/file2.wav

and I need an output directory like this:

/out/file0001.mp3
/out/file0002.mp3
/out/file0003.mp3
/out/file0004.mp3
/out/file0005.mp3
/out/file0006.mp3
/out/file0007.mp3
/out/file0008.mp3
/out/file0009.mp3

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
1

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':
        continue

    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
        os.system(ffmpeg_command)
| improve this answer | |
1

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

#!/bin/bash
i=0
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"
    done
done
| 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.