Linux – find all directories having less than x files inside

findlinux

Assume starting at some directory in the filesystem. This base directory has lots of subdirectories (not nested!). Each of the subdirectories has an arbitrary number of files withing.

How can I find all directories having e.g. less than 3 files inside using some shell command? The find command has some nice options for dealing with size of files, but I could not find anything regarding file count.

Best Answer

$ find . -type d | while read d; do if [ $(ls -1 "$d" | wc -l) -lt 3 ]; then echo $d; fi; done
Related Topic