Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wanted to find the number of image files within a directory. I ended up using this :

find . -type f  -exec file {} \; | grep -c -i 'image'

This feels like an inefficient way of doing it. I could think of another way to do it - using an OR statement, but I couldn't figure out from the man page how this could be done.

Any ideas how this could be done more efficiently? I don't want to execute the commands above on a directory with a rather large number of files and have it take forever.

share|improve this question

If you want to search for images by extension, you can use the following command:

find -type f -name *.gif -o -name *.jpg -o -name *.bmp

Of course, you need to list all extensions you are interested in.

To get the count, you can append | wc -l.

share|improve this answer
It's better to use -iname to match case insensitive – jollyroger Jun 18 '12 at 15:18

if you want to find files by mime-type of file in this case "image", you will need following command

   find . -type f -print0 | xargs -0 file -i | grep -i image | wc -l
share|improve this answer
He's already got it working. He's asking for a more efficient method. I suspect the find | xargs pattern is probably more efficient since it will only invoke file once where the original method invokes it once for every file found. grep -ci image would be more efficient than grep -i image | wc -l. – Ladadadada Jun 14 '12 at 10:40

You can get an efficiency improvement by using \+ instead of \;. The difference here is that \+ passes all found files to a single execution of file where \; executes file once for every file that was found.

find . -type f  -exec file {} \+ | grep -c -i 'image'

You will run into problems if it finds more files than file can take as arguments. You could pipe it through xargs with the --max-args option if that is the case.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.