1

I have never before needed to use find with multiple search terms. I found this:

find . -type f \( -name "*foo*" -o -name "*bar*" \)

..but it finds files which satisfy either of them, not both simultaneously.

Does anyone know how to adjust it so it finds files which simultaneously meet both requirements?

I try to avoid regex so would be nicer if it can be done without, but if not, as long as it works.

cardamom
  • 550
  • 1
    so, given a list of some files, e.g. foo.pl, bar.pl, foo.pm, asdf.pm, and hello.txt, which one(s) would you like to find? Obviously none them match both the patterns at the same time, because that's impossible, both patterns look at the ending of the filename, and there can only be one set of letters there. – ilkkachu Jul 13 '21 at 18:32
  • Sorry about that I fixed it. I wasn't even looking for endings – cardamom Jul 13 '21 at 19:10

1 Answers1

2

The equivalent for logical AND is -a. However, logical AND is the default anyhow, as the manual notes:

  Operators
          Operators  join  together  the other items within the expression.  
          They include for example -o (meaning logical OR) and -a (meaning logical AND).  
          Where an operator is missing, -a is assumed.

So you can simply chain the conditions like

find [paths] condition1 condition2 ...

ex.

find . -type f -name "*foo*" -name "*bar*"

In fact that's what you're implicitly doing with

find . -type f \( -name "*foo*" -o -name "*bar*" \)

which could have been written

find . -type f -a \( -name "*foo*" -o -name "*bar*" \)

Note that the parentheses are required in the -o case because of operator precedence with the default -print action; without parentheses it would look like

find . \( -type f -a -name "*foo*" \) -o \( -name "*bar*" -a -print \)

(which would only print entries matching -name "*bar*", and do so regardless of their type) - in the -a case, all the tests bind with the same precedence and parentheses are not necessary. See for example Operator precedence in a find command?

steeldriver
  • 81,074