Bash – Find list of directories one level deep from matching directory

bashdirectoryfindls

I'm trying to get a list of directories that are contained within a specific folder.

Given these example folders:

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

I'd like a command that will return:

XYZ
ABC
DEF
GHI

Essentially, I'm looking for the folders that are inside of wp-content/plugins/

Using find has gotten me the closest, but I can't use -maxdepth, because the folder is variably away from where I'm searching.

Running the following returns all of the child directories, recursively.

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

Best Answer

Just add a -prune so that the found directories are not descended into:

find . -type d -path '*/wp-content/plugins/*' -prune -print

You need to quote that *wp-content/plugins/* as it's also a shell glob.

If you want only the directory names as opposed to their full path, with GNU find, you can replace the -print with -printf '%f\n' or assuming the file paths don't contain newline characters, pipe the output of the above command to awk -F / '{print $NF}' or sed 's|.*/||' (also assuming the file paths contain only valid characters).

With zsh:

printf '%s\n' **/wp-content/plugins/*(D/:t)

**/ is any level of subdirectories (feature originating in zsh in the early nighties, and now found in most other shells like ksh93, tcsh, fish, bash, yash though generally under some option), (/) to select only files of type directory, D to include hidden (dot) ones, :t to get the tail (file name).

Related Question