Wednesday, November 4, 2009

How to exclude directories with find

To exclude directories with find,grep is the obvious choice  but it is not efficient.Following shows three ways to exclude directories with find

#Sample directories and file, the aim is to exclude directory /tmp/test/test1

$find /tmp/test
/tmp/test
/tmp/test/test1
/tmp/test/test1/test1.file
/tmp/test/test2
/tmp/test/test2/test2.file
/tmp/test/test3

(1) Simple most efficient way, but I can only get it working in ksh

$find /tmp/test/!(test1) -type f
/tmp/test/test2/test2.file
/tmp/test/test3

(2)With not expression “! “

$find /tmp/test ! -path "/tmp/test/test1*" -type f
/tmp/test/test2/test2.file
/tmp/test/test3

(3)With prune, which means exclude preceding path

$find /tmp/test  -path  /tmp/test/test1 -prune  -o -type f -print
/tmp/test/test2/test2.file
/tmp/test/test3