3

任务:列出目录本身的所有直接后代。

在 BSD (Mac OS) 上find . -type d -depth 1有效。

这是 Ubuntu 12.04(GNU findutils 4.4.2)的输出:

$ find . -type d -depth 1
find: warning: you have specified the -depth option after a non-option argument -type,
but options are not positional (-depth affects tests specified before it as well as 
those specified after it).  Please specify options before other arguments.

find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

好的,下次试试:

$ find . -depth 1 -type d
find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

嗯,好吧,也许它想要...

$ find -depth 1 . -type d
find: paths must precede expression: 1
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

显然不是,wtf,它应该需要......

$ find . -depth=1 -type d
find: unknown predicate `-depth=1'

不,这很明显。所以让我们尝试作为最后的手段......

$ find . -mindepth 1 -maxdepth 1 -type d
<my directories>

耶,成功!但是,呃,为什么……?

而且,作为一个额外的问题,为什么比BSD / OSX-mindepth 1 -maxdepth 1快得多?-depth 1

4

2 回答 2

3

不同版本的find使用-depth主要表示完全不同的事物:

  • -depth表示执行深度优先搜索(即在目录本身之前访问内容)。这与大多数初选不同,因为它不控制匹配的文件,而是执行搜索的方式。据我所知,所有版本都find支持这一点。

  • -depth n表示仅匹配深度为n的项目(即您想要的)。-depth这与后面没有数字时的含义完全不同,这可能会非常令人困惑。此外,并非所有版本都find支持这一点(OS X 支持,GNU findutils 显然不支持)。

-find n主要是有用的,但不幸的是不便携。如果您需要可移植性,我认为您会被-mindepth n -maxdepth n.

于 2014-02-27T06:53:54.903 回答
2

-depth选项不带参数:

-depth Process each directory's contents before the directory itself.

-name,-type期望后面跟着一些东西的选项,这不适用于-depth. 它更像是一个布尔选项。

于 2014-02-26T16:04:06.460 回答