Find directories containing a certain number of files

Categories: Linux, Bash

You could try this, to get the sub directory names and the number of files/directories they contain:

find . -maxdepth 1 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \;

If you want to do the same for all sub directories (recursive find) use this instead:

find . -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \;

To select those directories that have exactly 10 files:

find . -maxdepth 1 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \; | awk '$NF==10'

10 or more:

find . -maxdepth 1 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \; | awk '$NF>=10'

10 or less:

find . -maxdepth 1 -type d -exec bash -c "echo -ne '{} '; ls '{}' | wc -l" \; | awk '$NF<=10'

If you want to keep only the directory name (for example of you want to pipe it to another process downstream as @evilsoup suggested) you can use this:

find . -maxdepth 1 -type d -exec bash -c "echo -ne '{}\t'; ls '{}' | wc -l" \; | awk -F"\t" '$NF<=10{print $1}'

References:

https://superuser.com/questions/617050/find-directories-containing-a-certain-number-of-files

«
»