bashloopsmp3subdirectoryflac

How do I convert a directory (including multiple subdirectories) of .flac files to .mp3s using Bash?


I have a root directory with subdirectories, all containing .flac files. I would like to convert all the .flac files to .mp3 files, and delete the .flac files afterwards, so they are not taking up excess storage space.

I have the following command to convert the .flac files and remove them, which works well:

for f in *.flac; do flac -cd "$f" | lame -b 320 - "${f%.*}".mp3; done && rm -Rfv ./*.flac

Can you please help with a command loops that over the root directory and subdirectories and performs the conversion and deletion afterwards? Thank you.


Solution

  • Just set the globstar option and use the pattern **/*.flac to match all *.flac files in the current directory and in its subdirectories. Also, you may want to change the logic to remove converted flac files.

    #!/bin/bash
    
    shopt -s globstar
    for f in **/*.flac; do
        flac -cd "$f" | lame -b 320 - "${f%.*}".mp3 # && rm "$f"
    done
    

    Drop the # before && rm "$f" after making sure it will work