Linux: Find Command exclude directories from searching

As with most Linux commands, there are multiple ways to achieve this end result and it does not require any difficult commands to be remembered of. You only need pure logic to work it out. Let’s look at a few ways to do this.

See the example  below:

To demonstrate this, consider the example files and directories as below

“alpha“, “beta” and “com” directories.
example.com : The test file in all directories.

Lets see the output:

# find -iname example

./beta/example.com

./com/example.com

./alpha/example.com

Method 1 : Using “! -path”

# find -iname example.com ! -path ./beta/*

./com/example.com

./alpha/example.com

Method 2 : Using the option “-prune -o”

We can exclude directories by using the help of “path“, “prune“, “o” and “print” switches with find command.
See the example:

# find ./ -path ./beta/* -prune -o -iname example.com -print

./com/example.com

./alpha/example.com

The directory “beta” will be excluded from the find search!

Method 3 : Inverse grep “grep -v” option

Yes, it’s very simple. We can ignore the location by using inverse grep “grep -v” option.

See the example:

# find -iname example.com|grep -v beta

./com/example.com

./alpha/example.com

Excluding multiples directories

Similar way we can exclude multiple directories also. See the sample outputs:

# find -iname example.com ! -path ./beta/* ! -path ./alpha?*

./com/example.com

Or

# find -iname example.com | egrep -v “beta|alpha”

./com/example.com

That’s it.If you have any other method to achieve this result, feel free to share. 🙂

 

You may also like...

1 Response

  1. Bradlin Gerard says:

    Good and helpful Post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.