Categories
Bash Shell Scripts Unix Admin

bash : search multiple file patterns using single find command

Using a combination of patterns with “-o” and/or -“a” (which OR the pattern or AND the pattern) in find command, one can search for various patterns or combine various conditions.

One reader asked how find can be used to find various file patterns. For example in a directory which could be littered with various logs and other files, how do I use a single find command to find all shell scripts, perl scripts and say php scripts. Simple answer is to use multiple -name arguments combined with -o (or ORed) and if needed with -a (or ANDed). Other find conditions (like -mtime, -type etc) can be combined as well. Let’s see an example.

unixite@theunixtips:~/test> ls -1
1.dat
2.txt
33.sh
3.sh
4.pl
5.php
unixite@theunixtips:~/test> find . ( -name "*.sh" -o -name "*.pl" -o -name "*.php" )
./3.sh
./33.sh
./4.pl
./5.php

With above command more patterns can be specified where more ANDing or ORing can be done. For example to search all scripts that start with 3.

unixite@theunixtips:~/test> find . ( ( -name "*.sh" -o -name "*.pl" -o -name "*.php" ) -a ( -name "3*" ) )
./3.sh
./33.sh

Using this user can combine many other conditions (e.g. search for the files with size ranges between 100K and 500K). Or simply if one has a simple pattern to search.

unixite@theunixtips:~/test> find . -name "*.sh" -o -name "*.pl" -o -name "*.php"
./3.sh
./33.sh
./4.pl
./5.php

Note: The brackets have to be escaped correctly and also there should be space between brackets and the patterns.