以递归方式运行bash脚本并对子目录中的所有文件执行操作

时间:2018-06-17 14:10:40

标签: bash

我正在尝试使用ffmpeg将flac文件转换为wav文件。 flac文件位于各个子目录中。

/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

脚本运行后我想要的是以下

/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

我可以让我的脚本在一个目录中工作,但是我很难从顶级目录(speech_files)运行它并在所有子目录中运行它。下面是我正在使用的脚本。

#!/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

2 个答案:

答案 0 :(得分:0)

仅使用bash:

#!/bin/bash

DIR="/.../speech_files"

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

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

使用递归且更高效的find来执行此类任务:

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

答案 1 :(得分:0)

使用顶级目录中的find并使用* .flac。

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