Linux – Find directories that contain more than one file of the same extension

command linefindlinux

I’m using Debian 8.0 and would like for example to find directories that contain more than 1 .mkv file. I tried this and it failed:

find -type d -exec find {} -name '*.mkv' | wc -l\;

There is a similar Q&A here on SuperUser, which I wasn’t able to adapt. This didn't work for me either:

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

The error message points to a syntax error:

bash: -c: line 0: syntax error near unexpected token `('

The reason for this is that the directory has a name like this:

Directory With Space and (Brackets)

Best Answer

I'd suggest instructing find to look for all the files and print out the containing directory of each match, so you won't need to worry about parsing weird strings. Then use uniq to count the duplicates and awk to filter on the first field printing out those occurring more than once. e.g.

find . -type f -iname '*.mkv' -printf '%h\n'|sort|uniq -c | awk '$1 > 1'
Related Question