简体   繁体   中英

Running a bash script recursively and performing operations on all files within the subdirectories

I'm trying to convert flac files into wav files using ffmpeg. The flac files are located in various subdirectories.

/speech_files
/speech_files/201/speech1.flac
/speech_files/201/speech2.flac
/speech_files/44/speech45.flac
/speech_files/44/speech109.flac
/speech_files/66/speech200.flac
/speech_files/66/speech33.flac

What I want after the script runs is the following

/speech_files
/speech_files/201/speech1.wav
/speech_files/201/speech2.wav
/speech_files/44/speech45.wav
/speech_files/44/speech109.wav
/speech_files/66/speech200.wav
/speech_files/66/speech33.wav

I can get my script to work within one directory but I'm having a hard time getting it to run from the top level directory ( speech_files ) and work it's way through all the subdirectories. Below is the script I'm using.

#!/bin/bash

for f in "./"/*
do
    filename=$(basename $f)
    if [[ ($filename == *.flac) ]]; then
        new_file=${filename%?????}
        file_ext="_mono_16000.wav"
        wav_file_ext=".wav"
        ffmpeg -i $filename $new_shits$wav_file_ext
        ffmpeg -i $new_file$wav_file_ext -ac 1 -ar 16000 $new_file$file_ext
        rm -f $filename
        rm -f $new_file$wav_file_ext
    fi
done

Using bash only :

#!/bin/bash

DIR="/.../speech_files"

process() {
    filename=$(basename "$1")
    # ...
}

for f in n "${DIR}"/*/*.flac; do
    process "$f"
done

Using find which is recursive and more efficient to do that kind of task to me :

find "${DIR}" -type f -a -iname "*.flac" -exec ... {} \;

Use find from the top level directory and filter by using *.flac.

for f in $(find . -name "*.flac"); do
    echo "$f" # f points to each file
    # do your logic here
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM