使用 Unix 的 find 命令查找匹配名称的目录但不查找具有相同名称的子目录

Gab*_*mbe 11 linux unix command-line find

编辑:我错误地歪曲了我的问题。一个更准确的例子现在出现在下面。

我想递归遍历目标目录中的所有目录,并在找到第一个 .git 目录后停止每个递归调用。

例如,如果我们有这些路径:

/home/code/twitter/.git/
/home/code/twitter/some_file
/home/code/twitter/some_other_file 
/home/code/facebook/.git/
/home/code/facebook/another_file
/home/code/configs/.git/
/home/code/configs/some_module/.git/
/home/code/configs/another_module/.git/
/home/code/some/unknown/depth/until/this/git/dir/.git/
/home/code/some/unknown/depth/until/this/git/dir/some_file
Run Code Online (Sandbox Code Playgroud)

我只想要结果中的这些行:

/home/code/twitter
/home/code/facebook
/home/code/configs
/home/code/some/unknown/depth/until/this/git/dir/
Run Code Online (Sandbox Code Playgroud)

-maxdepth这里对我没有帮助,因为我不知道我的目标的每个子目录的第一个 .git 目录有多深。

我以为find /home/code -type d -name .git -prune会这样做,但它对我不起作用。我错过了什么?

Dig*_*ris 7

听起来你想要这个-maxdepth选项。

find /home/code -maxdepth 2 -type d -name .git


Pax*_*ali 6

这很棘手, -maxdepth 和递归技巧在这里没有帮助,但这就是我要做的:

find /home/code -type d -name ".git" | grep -v '\.git/'
Run Code Online (Sandbox Code Playgroud)

用英语:找到所有名为“.git”的目录,并过滤掉结果列表中包含“.git/”(点git斜杠)的任何出现的情况。

上面的命令行适用于所有 UNIX 系统,但是,如果您可以断言您的查找将是“GNU find”,那么这也将有效:

find /home/code -type d -name ".git" ! -path "*/.git/*"
Run Code Online (Sandbox Code Playgroud)

玩得开心。