How to exclude directories or files from a 'find' search in Linux?

Published on Aug. 22, 2023, 12:17 p.m.

To exclude directories or files from a ‘find’ search in Linux, you can use the ‘-not’ option along with other options that specify the directories or files you want to exclude.

For example:

find /path/to/directory -type f -not -path "/path/to/directory/exclude_directory/*" -name "*.txt"

In this example command, ‘-not’ is used to exclude the ‘/path/to/directory/exclude_directory/’ directory and all its subdirectories. The command will find all files with the extension ‘*.txt’ in the specified directory and its subdirectories, excluding the files that are located in the excluded directory.

You can also use the ‘-prune’ option to exclude a directory and its subdirectories from the search entirely, like this:

find /path/to/directory -path "/path/to/directory/exclude_directory" -prune -o -type f -name "*.txt" -print

In this example command, ‘-path “/path/to/directory/exclude_directory” -prune’ is used to exclude the ‘/path/to/directory/exclude_directory/’ directory and all its subdirectories from the search. The ‘-o’ option indicates an OR condition, allowing the search to continue for other directories that are not excluded.

Tags: