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
2009-05-02 21:37:09
Slightly shorter syntax for the same thing: find . -type f -exec dirname {} \; | sort -u
David Zaslavsky
2009-05-02 21:43:15
@Emil, I don't know what your system is, but it works on Linux, SunOS and Mac OS X.
Paul Tomblin
2009-05-02 21:47:59
Terribly sorry. An unmatched single quote caused early termination. Totally my fault.
Emil H
2009-05-02 21:48:47
+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
2009-05-02 21:38:45
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
2009-05-02 21:50:25
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
2009-05-02 23:18:19
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
2009-05-02 23:34:43