tags:

views:

750

answers:

3

I have a directory containing multiple subdirectories. I want to list only those subdirectories that contain at least one file. How can I do that?

A: 

How about:

find /nominated/directory -type f |
sed 's%/[^/]*$%% |
sort -u

Find files - drop file name part - sort uniquely.

It won't list subdirectories that contain only other sub-sub-directories.

Jonathan Leffler
+2  A: 
find . -type f -print0 | xargs -0 -n 1 dirname | sort -u
Paul Tomblin
Slightly shorter syntax for the same thing: find . -type f -exec dirname {} \; | sort -u
David Zaslavsky
@Emil, I don't know what your system is, but it works on Linux, SunOS and Mac OS X.
Paul Tomblin
Terribly sorry. An unmatched single quote caused early termination. Totally my fault.
Emil H
+5  A: 
 find . -mindepth 1 -maxdepth 1 -not -empty -type d

will give you all nonempty directories. If you want to exclude directories that contain only other directories (but no files), one of the other answers might be better...

David Zaslavsky
The -mindepth and -maxdepth options restrict this to only the immediate subdirectories. Adjust these to affect at which level results are returned. Leaving them off will find all subdirectories at any level.
Naaff
and remember that -not is GNU-stuff. To be portable, use ! instead of -not (really; I don't see why you wouldn't just always use ! instead of -not, seeing as -not gives you no advantage whatsoever)
lhunath
Because ! looks like it should be a shell metacharacter and I can never remember whether I have to quote it or not ;-) but you are right about it being more portable. (I guess since this answer was accepted, GNU-specific syntax works for the OP)
David Zaslavsky