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

0

1

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).

Bob Ortiz

Posted 2018-02-06T22:50:44.590

Reputation: 119

Answers

3

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).

Andrew Domaszek

Posted 2018-02-06T22:50:44.590

Reputation: 491

2

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.

Kamil Maciorowski

Posted 2018-02-06T22:50:44.590

Reputation: 38 429