Exclude a directory or multiple directories while using find command

Is it possible to exclude a directory with find command?

Yep, the command FIND has wide range of options to search what you actually looking for.

I have already listed different switches and its usages with examples. Here we go for excluding some directories from our find job.

In some cases, we have to exclude some directories from our search pattern!

Quick view on “Find command and switches

 

There are different ways to exclude a directory or multiple directories in FIND command. Here I’m listing some methods!

To explain this, I created the following directories and files:

  •  “cry“, “bit” and “com” directories.
  • ” findme “: The test file in all directories.

Lets see the output:

# find -iname findme
./bit/findme
./com/findme
./cry/findme

Method 1 : 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 ./bit/* -prune -o -iname findme -print
./com/findme
./cry/findme

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

Method 2 : Using “! -path”

This is not much complicated compared to first method. See the example pasted below:

# find -iname findme ! -path ./bit/*
./com/findme
./cry/findme

Method 3 : Simple 🙂

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

See the example:

# find -iname findme|grep -v bit
./com/findme
./cry/findme

Excluding multiples directories

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

# find -iname findme ! -path ./bit/* ! -path ./cry?*
./com/findme

Or

# find -iname findme | egrep -v "bit|cry"
./com/findme

That’s it. Compose it your own ways!!

Related

1, 10+ commonly using find command switches with example Unix/Linux
2, How to find the total number of connections for a cPanel account from the log files
3, How to check all opened files in a directory – lsof command

Post navigation

Arunlal Ashok

Linux Systems Architect at Endurance International Group. I know her (Linux) since many years. Linux lover. Like to play on Linux console. I started this blog to share and discuss Linux thoughts.

Always happy for an open discussion! Write to arun (@) crybit (dot) com. Check about me for more details. About this blog and our strong members, check The team CryBit.com

Leave a Reply

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