任务:列出作为目录本身的目录的所有直接后代。
在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>
是的,成功!但是,呃,为什么......?
而且,作为一个额外的问题,为什么-mindepth 1 -maxdepth 1
比BSD / OSX上的-depth 1
快得多?
答案 0 :(得分:3)
find
的不同版本使用-depth
主要内容来表示完全不同的内容:
-depth
表示执行深度优先搜索(即访问目录本身之前的内容)。这与大多数原色不同,因为它不控制哪些文件匹配,而是如何执行搜索。据我所知,find
的所有版本都支持此功能。
-depth n
表示仅匹配 n 深度的项目(即您想要的内容)。这与-depth
完全不同,当它没有跟随数字时,这可能会非常混乱。此外,并非所有版本的find
都支持此功能(OS X的支持,GNU findutils'显然不支持)。
-find n
主要版本很有用,但遗憾的是不可移植。如果您需要便携性,我认为您会遇到-mindepth n -maxdepth n
。
答案 1 :(得分:2)
-depth
选项不带参数:
-depth Process each directory's contents before the directory itself.
-name
,-type
之类的选项需要后跟某些内容,这不适用于-depth
。它更像是一个布尔选项。