HOME BLOG

How to find files in a folder while excluding those in certain subfolders

Posted on: March 11th, 2021 by Olu No Comments

Hi folks,

Recently in the course of work I had to find lots of files in a certain folder while excluding files in certain subfolders. I had to do a bit of research on how to do this in Linux-like environments. So I thought I’ll share.

So, let’s assume that in the current directory there are subdirectories s1, s2, s3, etc., each containing .txt files. Now assume you want to recursively find all .txt files in the current directory, but exclude all those in s2 and s3 subdirectories.

Here’s a command you can use to accomplish this using the find command.

 

find . -name '*.txt' -not \( -path './sub2/*' -o -path './sub3/*' \)

 

Note that the -o means OR logic. The \( and \) allows us wrap multiple conditions together to form a compound condition and the -not means NOT logic. Also of interest is the -path flag which allows you to match a pattern in the path of a file.

That’s all for now. Till next time, happy software development.

Leave a Reply