Bash:查找少于 x 个文件的文件夹

Led*_*eda 7 linux bash shell find

我将如何查找目录中包含少于 x 个.flac文件的所有文件夹?

Gil*_*il' 9

  • 对于每个子目录,如果子目录中最多有 42 个.flac文件,则打印子目录名称。要对目录执行命令,请替换-print-exec … \;. 符合 POSIX。

    find . -type d -exec sh -c 'set -- "$0"/*.flac; [ $# -le 42 ]' {} \; -print
    
    Run Code Online (Sandbox Code Playgroud)

    请注意,此命令不适用于搜索包含零个.flac文件的目录("$0/*.flac"扩展为至少一个单词)。相反,使用

    find . -type d -exec sh -c 'set -- "$0"/*.flac; ! [ -e "$1" ]' {} \; -print
    
    Run Code Online (Sandbox Code Playgroud)
  • zsh 中的相同算法。**/*递归扩展到当前目录及其子目录中的所有文件。**/*(/)限制对目录的扩展。{.,**/*}(/)添加当前目录。最后,(e:…:)将扩展限制为 shell 代码返回 0 的匹配项。

    echo {.,**/*}(/e:'set -- $REPLY/*.flac(N); ((# <= 42))':)
    
    Run Code Online (Sandbox Code Playgroud)

    为了便于阅读,这可以分为两个步骤。

    few_flacs () { set -- $REPLY/*.flac(N); ((# <= 42)); }
    echo {.,**/*}(/+few_flacs)
    
    Run Code Online (Sandbox Code Playgroud)

更新日志
?• 正确处理 x=0。