Linux – Find directories containing a certain number of files

findlinux

Was hoping I would be able to do this with the find command but I can see no test in the manual for doing what I want. I would like to be able to find any directories in the working directory that contain less-than, more-than or exactly the count I specify.

find . -filecount +10 # any directory with more than 10 entries
find . -filecount 20 # any directory with exactly 20 entries

But alas there is no such option.

Best Answer

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}'