How to recursively find folders on a Linux system, that contains folders only?

I'm trying to work out a command that recursively finds directories that only contain one or more directories on the same level. Preferably with the find command. Like find . -type d.

For example, in the following file structure:

/tmp/folder1/folder1a/test.jpg
/tmp/folder1/file1a.tmp
/tmp/folder2/folder2a/test.jpg
/tmp/folder3/folder3a/
/tmp/folder3/folder3b/file.jpg

I'd like to hit on folder2 and folder3 only since it does not contain files itself, it only contains folders (with files).

0

2 Answers

comm -23 <(find . -type d ! -empty | sort -u) <(find . -type f -printf '%h\n' | sort -u)

This is a list of non-empty folders (at least one thing in it) excluding those that contain any files. If you also want to exclude things like pipes and symlinks you could use ! -type d instead of -type f. It cannot be done in a single find statement because find cannot match on complex content criteria (this is not XPath).

0

If I get you right, this should do it:

find . -type d ! -empty -exec sh -c '\
[ -z "`find "$1" -maxdepth 1 -mindepth 1 ! -type d -print -quit`" ]\
' sh {} \; -print

Because of -empty, -maxdepth, -mindepth and -quit, which are not in POSIX, the solution may not work in your OS (-print -quit is only to speed things up, you can omit this fragment; -maxdepth 1 -mindepth 1 is important though).

The trick is to run a separate shell for every non-empty directory, that checks (non-recursively) if the directory doesn't contain any non-directory. This is done with -exec sh … \;, it acts as a test here. If the directory doesn't contain any non-directory then the output of the inner find is empty, so the test ([ -z … ]) returns exit status 0, sh returns 0, -exec is true.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like