Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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
add comment

3 Answers

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
add comment

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
1  
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
add comment

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
add comment

Your Answer

 
discard

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.