Tuesday, September 9, 2008

Linux find command and logical operators


Some of the example to show how we can use logical operators with linux find command.

To find any file whose name ends with either 'sh' or 'pl'

$ find . -type f \( -iname "*.sh" -or -iname "*.pl" \)

To find .txt files that are writeable by "others"

$ find . -type f \( -iname "*.txt" -and -perm -o=w \)

To find .txt files but exclude the ones which are writeable by "others"

$
find . -type f \( -iname "*.txt" ! -perm -o=w \)

or

some find versions support "-not" as well

$
find . -type f \( -iname "*.txt" -not -perm -o=w \)

Remember: The parentheses must be escaped with a backslash, "\(" and "\)", to prevent them from being interpreted as special shell characters.

1 comment:

Karan Bohra said...

The -or -and -not are not POSIX-find compliant.

-or -> -o
-and -> -a
-not -> ! (may need to backslash it in some shells, e.g., csh if there is nonspc
character immmediately following the !, to get over the history mechanism of csh)

And the -and is rarely used if ever, since the concatenation of commands
an ANDing is implicit.

-iname is also non-POSIX. we need to use the wildcards.

To find any file whose name ends with either 'sh' or 'pl'

$ find . -type f \( -name "*.[sS][hH]" -o -name "*.[pP][lL]" \)

To find .txt files that are writable by "others"

Note there's no need of the parentheses here as the ANDing is implicit

$ find . -type f -name "*.[tT][xX][tT]" -perm -o=w

To find .txt files but exclude the ones which are writable by "others"

$ find . -type f -name "*.[tT][xX][tT]" ! -perm -o=w

© Jadu Saikia www.UNIXCL.com