Search code examples
bashunixfindbatch-processinggnu-findutils

Batch-process files with find in multiple directories


I have a directory with several subdirs which contain .flac files. I want to batch convert them to .mp3. The path names contain spaces. Now I want to do something like this

find . -type f -regex .*.flac -exec ffmpeg -i {} -c:a mp3 -b:a 320k  \;

But the question is, how can I use {} and substitute flac for mp3 to give ffmpeg an output file name? In bash, one could use variable substitution ${file%.flac}.mp3, but I cannot apply this here. sed-based approaches don't seem to work with find either. Is there any simple solution to this?


Solution

  • If you're using bash, I'd use globstar, which will expand to the list of all your .flac files:

    shopt -s globstar nullglob
    for file in **/*.flac; do
        [[ -f $file ]] || continue
        out_file=${file%.flac}.mp3
        ffmpeg # your options here, using "$out_file"
    done
    

    The check [[ -f $file ]] skips any directories that end in .flac. You could probably skip this if you don't have any of those.

    I've also enabled the nullglob shell option, so that a pattern which doesn't match any files expands to nothing (so the loop won't run).