2

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.

3 Answers 3

6

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.

1
  • 1
    It's better to use -iname to match case insensitive
    – jollyroger
    Jun 18, 2012 at 15:18
5

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.

1

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
1
  • 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, 2012 at 10:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .