Home > Enterprise >  Need to find files with multiples arguments in bash
Need to find files with multiples arguments in bash

Time:06-30

I've done this atm, I need to find in the main directory and in the sub-directory everything starting with the letter 'a', every files ending with 'z' and every files starting with 'z' and ending with 'a!'.
find . -name "a*" | find . "*z" -type f | find . "z*a!" -type f
I tried to be as clear as possible, sorry if it wasn't clear enough.

CodePudding user response:

find . -type f \( -name 'a*' -or -name '*z' -or -name 'z*a!' \)

Use -o instead of -or for POSIX compliance.

If you really want to also find links, directories, pipes etc. starting with a but only files matching the remaining conditions, you can do

find . -name 'a*' -or -type f \(-name '*z' -or -name 'z*a!' \)

CodePudding user response:

TL;DR

find . -name 'a*' -o -type f \( -name '*z' -o -name 'z*a!' \)

Explanations:

The find logical operators are -a (AND) and -o (OR). You use them to combine elementary tests. Note that because of operator's precedence you sometimes need parentheses and that they must be escaped (with \) to prevent their interpretation by the shell. Your test is:

  • everything starting with the letter 'a': -name 'a*'.
  • every files ending with 'z': -type f -a -name '*z'.
  • every files starting with 'z' and ending with 'a!': -type f -a -name 'z*a!'.

So the complete test could be:

-name 'a*' -o \( -type f -a -name '*z' \) -o \( -type f -a -name 'z*a!' \)

As -a is the default we can omit it, and as -type f (file) is common to the two last terms of the disjunction we can factor it:

-name 'a*' -o -type f \( -name '*z' -o -name 'z*a!' \)
  • Related