从匹配目录中查找一层深的目录列表

Nic*_*ick 15 ls bash directory find

我正在尝试获取包含在特定文件夹中的目录列表。

鉴于这些示例文件夹:

foo/bar/test
foo/bar/test/css
foo/bar/wp-content/plugins/XYZ
foo/bar/wp-content/plugins/XYZ/js
foo/bar/wp-content/plugins/XYZ/css
baz/wp-content/plugins/ABC
baz/wp-content/plugins/ABC/inc
baz/wp-content/plugins/ABC/inc/lib
baz/wp-content/plugins/DEF
bat/bar/foo/blog/wp-content/plugins/GHI
Run Code Online (Sandbox Code Playgroud)

我想要一个将返回的命令:

XYZ
ABC
DEF
GHI
Run Code Online (Sandbox Code Playgroud)

本质上,我正在寻找 wp-content/plugins/ 中的文件夹

Usingfind使我最接近,但我不能使用-maxdepth,因为该文件夹离我正在搜索的位置很远。

运行以下命令以递归方式返回所有子目录。

find -type d -path *wp-content/plugins/*

foo/bar/wp-content/plugins/XYZ
foo/bar/wp-content/plugins/XYZ/js
foo/bar/wp-content/plugins/XYZ/css
baz/wp-content/plugins/ABC
baz/wp-content/plugins/ABC/inc
baz/wp-content/plugins/ABC/inc/lib
baz/wp-content/plugins/DEF
bat/bar/foo/blog/wp-content/plugins/GHI
Run Code Online (Sandbox Code Playgroud)

Sté*_*las 16

只需添加一个,-prune以便找到的目录不会下降到:

find . -type d -path '*/wp-content/plugins/*' -prune -print
Run Code Online (Sandbox Code Playgroud)

您需要引用它,*wp-content/plugins/*因为它也是一个 shell glob。

如果您只想要目录名称而不是完整路径,则可以使用 GNUfind替换-printwith-printf '%f\n'或假设文件路径不包含换行符,将上述命令的输出通过管道传送到awk -F / '{print $NF}'or sed 's|.*/||'(还假设文件路径包含仅有效字符)。

zsh

printf '%s\n' **/wp-content/plugins/*(D/:t)
Run Code Online (Sandbox Code Playgroud)

**/是子目录的任何级别(功能起源于zsh早期睡衣,现在在大多数其他炮弹发现喜欢ksh93tcshfishbashyash在某些选项,虽然通常情况下),(/)只选择类型的文件目录D包括隐藏(点)的,:t以获取尾部(文件名)。


Dop*_*oti 6

你可以find递归,排序:

find / -type d -path *wp-content/plugins -exec find {} -maxdepth 1 -mindepth 1 -type d \;
Run Code Online (Sandbox Code Playgroud)