使用 find 获取目录名称列表

joa*_*him 51 directory find

我知道我可以这样做来获取目录名称列表:

find . -type d -maxdepth 1 
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

.
./foo
./bar
Run Code Online (Sandbox Code Playgroud)

我更喜欢没有./. 有没有办法让 find 只输出原始名称?

我尝试将列表发送到 stat 以对其进行格式化,但这只是给了我相同的结果:

find . -type d -maxdepth 1 -print0 | xargs -0 stat -f '%N'
Run Code Online (Sandbox Code Playgroud)

Tho*_*hor 54

使用 GNU,find您可以使用以下-printf选项:

find . -maxdepth 1 -type d -printf '%f\n'
Run Code Online (Sandbox Code Playgroud)

正如帕维所指出的那样?在评论中,如果您不想列出当前目录,请添加-mindepth 1,例如:

find . -mindepth 1 -maxdepth 1 -type d -printf '%f\n'
Run Code Online (Sandbox Code Playgroud)

  • 如果你想去掉 `.`,还可以添加 `-mindepth 1` (2认同)

Lev*_*von 22

更新:

更短的替代方案:

 find . -maxdepth 1 -type d | cut -c 3-
Run Code Online (Sandbox Code Playgroud)

会给你名字,每行一个,没有任何斜线

  • @downvoter .. 没有***解释的downvote ***对*任何人*(OP,SO或我)都没有帮助。这是 OP 问题的功能解决方案。如果指出错误或改进答案,我很乐意纠正错误,但这需要*建设性*的反馈,而不仅仅是匿名的“点击”。 (6认同)
  • 当你的答案包括解析“ls”时,我是投了反对票的人。与此同时,我在另一个答案上发布了一个关于[为什么这是一个坏主意](http://mywiki.wooledge.org/ParsingLs)的链接,该链接后来被删除。当时只有两个答案,原因似乎很明显。我很高兴你指出了其中的歧义,这是我的解释。根据记录,我将反对票转为赞成票,因为我同意您当前的答案。 (2认同)

jor*_*anm 9

使用 GNU find,您可以使用 -mindepth 来防止 find 匹配当前目录:

find . -type d -maxdepth 1 -mindepth 1
Run Code Online (Sandbox Code Playgroud)

由于您不是递归地执行此操作,因此可以使用 bash glob:

echo */
Run Code Online (Sandbox Code Playgroud)

向 glob 添加尾随 / 将导致仅匹配目录。


小智 8

我宁愿使用:

 find ./ -type d -maxdepth 1 -exec basename {} \;
Run Code Online (Sandbox Code Playgroud)


Bir*_*rei 6

让我们sed删除这两个字符:

find . -maxdepth 1 -type d | sed -e 's/^\.\///'
Run Code Online (Sandbox Code Playgroud)