bash - 如果找到匹配项,则停止查找命令的递归

标签 bash gnu-findutils

使用 GNU findutils,我需要在目录树中搜索某个文件。如果已找到给定分支的文件,我想防止 find 进一步递归到分支中。假设我要查找文件 foo,这是我的目录树:

├── a
│   ├── a1
│   │   └── foo
│   └── foo
├── b
└── c
    └── foo

鉴于我正在搜索上面的树,我想找到 a/foo 和 c/foo。但是,我不想找到 a/a1/foo,因为我已经在 a1 的父目录中找到了 foo。 看来我应该在 find 命令中使用 -prune 标志,我找到了这个链接 https://unix.stackexchange.com/questions/24557/how-do-i-stop-a-find-from-descending-into-found-directories ,例如,但我无法让它工作。我的尝试包括:

$ find -name foo -type f -prune
./a/a1/foo <- Unwanted hit
./a/foo
./c/foo

$ find -name foo -type f -prune -exec find ../foo -type f {} \;
find: paths must precede expression: ./a/a1/foo
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
find: paths must precede expression: ./a/foo
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
find: paths must precede expression: ./c/foo
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

最佳答案

这将打印包含 foo 的目录,并且不会在它们的子目录中递归:

find -type d -exec test -f {}/foo \; -print -prune

{}/foo 的行为 is explicitly left undefined by POSIX :

If a utility_name or argument string contains the two characters "{}", but not just the two characters "{}", it is implementation-defined whether find replaces those two characters or uses the string without change.

但与 GNU find 一起按预期工作(并且您用 标记了问题)。正如 Kamil Cuk 在评论中正确建议的那样,如果您使用的是非 GNU find 或者如果您想要一个更便携的解决方案,请使用:

find -type d -exec sh -c 'test -f "$1"/foo' -- {} \; -print -prune

关于bash - 如果找到匹配项,则停止查找命令的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54579276/

相关文章:

Linux:查找包含 4 或 5 个字符的文件名

linux - 如何查找最近 x 分钟内修改的文件(find -mmin 无法按预期工作)

Unix find -mtime {一个负值或正值}

bash - 查找最近 30 分钟内未访问/修改的文件?

linux:计时命令,将 stdout 和 stderr 重定向到日志文件并将其显示在终端中

linux - Shell 脚本 (BASH) 中的多处理

linux - 将文件修改日期和 "grep"结果通过 "find"组合在一行中

regex - 如何查找名称中包含换行符的文件

bash - Bash 中 ". filename"(句点空间文件名)的含义是什么?

regex - 带反引号的 grep 正则表达式匹配所有行