Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I would like to find all png AND jpg files and used the following command and no results are returned however if I replace -a with -o it shows me the list of files. Why is that?

`find . -maxdepth 1 \( -iname \*\.png -a -iname \*\.jpg \)
share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

A logic error. What you're telling find is:

find, in this folder, all files that are (PNG and JPG)

But, of course, there are no files that are both at the same time, which is why the -o works:

find, in this folder, all files that are (PNG or JPG)

When constructing these queries just imagine find passing each file to the test. Then apply boolean logic. So for example:

  • It finds a .txt file. It's not a PNG (false), and not a JPG (false), so false && false equals false

  • It finds is a .png file. It's a PNG (true), and not a JPG (false), so true && false equals false

  • It finds is a .jpg file. It's not a PNG (false), and it's a JPG (true), so false && true equals false

  • If you use the -o switch, and it finds a .png file, then it's a PNG (true) and it's not a JPG (false), so true || false equals true.

share|improve this answer
    
Thanks slhck. How would I construct it correctly so that it would find files that are only PNG and JPG? I have a thousand files that are either text files, documents of sorts, images (PNG, JPG), etc. –  PeanutsMonkey Jan 15 '13 at 5:01
    
With -o instead of -a, like I said. If you don't get any results, then you're searching in the wrong directory. –  slhck Jan 15 '13 at 6:16
    
So does it treat each query independently i.e. -iname \*\.png is looked at as 1 query followed by the second query of -iname \*\.jpg? –  PeanutsMonkey Jan 15 '13 at 7:20
    
Yes. find will evaluate both "queries" to whether they're true or false, and then combine the result of both with the logic test (and/or). If the result is true, the file is found. As I wrote in my example, if the first test is true ("It's a PNG!") and the second is false ("It's not a JPG!"), this evaluates to true when combined with a logical or. –  slhck Jan 15 '13 at 7:23
add comment

-a is a logical AND meaning that the file name must end in both .PNG and .JPG to be true.

-o is a logical inclusive OR meaning the file name must end in .PNG or .JPG (or both) to be true.

share|improve this answer
    
Thanks parkydr. What would it be for both PNG and JPG? –  PeanutsMonkey Jan 15 '13 at 5:02
    
@PeanutsMonkey -o instead of -a, as I wrote in my answer as well. –  slhck Jan 15 '13 at 6:14
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.