【问题标题】:Running a bash script recursively and performing operations on all files within the subdirectories递归运行 bash 脚本并对子目录中的所有文件执行操作
【发布时间】:2018-06-17 14:10:40
【问题描述】:

我正在尝试使用 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

【问题讨论】:

标签: bash


【解决方案1】:

使用从顶级目录中查找并使用 *.flac 进行过滤。

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

【讨论】:

  • 无需使用for 循环来迭代find 输出,您有-exec 选项,它更安全。 for i in $(command) 可能会在文件名包含一些空格时导致错误。
  • 是的,有更好的选择可以让事情变得更快。如果编写更快的代码是唯一的标准,那么我会用“Java”或 c++ 之类的语言询问他/她并完成所有艰苦的工作。
  • 这不仅仅是为了更快地做事,for i in $(command) 是一种经常导致错误的坏做法(例如,当文件名包含空格时它不起作用)。这也是不重新发明轮子的问题:如果您选择使用find,则完全使用find
  • 如果你真的需要迭代命令的输出(这里不是这种情况),有很多更安全的方法,我建议你阅读:stackoverflow.com/a/19607361/2900196
  • 我在这里找到了一个不错的答案:How to loop through file names returned by find?
【解决方案2】:

仅使用 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 ... {} \;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 2015-02-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    相关资源
    最近更新 更多