How do I exclude a directory when using `find` in Linux?
To exclude a particular directory while searching with find
, you can use a combination of -prune
and -o
(logical OR). For example:
find . -type d -name "excluded_dir" -prune -o -type f -name "*.txt" -print
Explanation
-type d -name "excluded_dir" -prune
: This tellsfind
to skip (prune) any directory named"excluded_dir"
instead of descending into it.-o
(logical OR): Separates the prune condition from the actual search condition.-type f -name "*.txt" -print
: The main search logic—here, it finds and prints all*.txt
files.
As a result, excluded_dir
is ignored, and find
proceeds to look for text files in the rest of the directory tree. You can modify the pattern ("*.txt"
) or combine multiple conditions as needed.
More Complex Example
If you want to exclude multiple directories, you can chain pruning conditions:
find . \ \( -type d -name "node_modules" -prune \) -o \ \( -type d -name "vendor" -prune \) -o \ \( -type f -name "*.rb" -print \)
Here, both node_modules
and vendor
directories are skipped, and the command looks for Ruby files (*.rb
) everywhere else.
Further Learning
To build a solid foundation in scripting, algorithms, and coding patterns, consider these courses from DesignGurus.io:
- Grokking Data Structures & Algorithms for Coding Interviews – Master the crucial concepts that underpin efficient coding and problem-solving.
- Grokking the Coding Interview: Patterns for Coding Questions – Learn the most common patterns tested in technical interviews, enhancing your productivity in any programming language.
By understanding powerful Linux commands like find
and strengthening your problem-solving skills, you’ll be well-prepared for both day-to-day development tasks and challenging coding interviews.