Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
As Linux users, we frequently perform various operations on file systems. For example, one of the common operations is searching files. This simple task becomes time-consuming if the system has a large number of files. However, we can make it efficient by excluding certain directories from the search path.
In this tutorial, we’ll discuss the various ways to achieve this with the find command.
Let’s create a set of files and directories to use as an example:
$ mkdir mp3 jpeg txt
$ touch mp3/1.mp3 mp3/2.mp3 mp3/3.mp3
$ touch jpeg/1.jpeg jpeg/2.jpeg jpeg/3.jpeg
$ touch txt/1.txt txt/2.txt txt/3.txt
Let’s now look at the directory tree we just created:
$ tree
.
├── jpeg
│ ├── 1.jpeg
│ ├── 2.jpeg
│ └── 3.jpeg
├── mp3
│ ├── 1.mp3
│ ├── 2.mp3
│ └── 3.mp3
└── txt
├── 1.txt
├── 2.txt
└── 3.txt
We can use the -prune option of the find command to exclude a certain path:
$ find . -path ./jpeg -prune -o -print
.
./txt
./txt/3.txt
./txt/2.txt
./txt/1.txt
./mp3
./mp3/1.mp3
./mp3/2.mp3
./mp3/3.mp3
In the above example, the find command performs a search in all directories except jpeg.
We can also exclude multiple paths using the -o operator:
$ find . \( -path ./jpeg -prune -o -path ./mp3 -prune \) -o -print
.
./txt
./txt/3.txt
./txt/2.txt
./txt/1.txt
In the above example, we are using the -o operator to exclude jpeg and mp3 directories.
The find command also provides the -not operator. We can use it to exclude a directory from a search path:
$ find . -type f -not -path '*/mp3/*'
./jpeg/3.jpeg
./jpeg/2.jpeg
./jpeg/1.jpeg
./txt/3.txt
./txt/2.txt
./txt/1.txt
In the above example, we’re using the -not operator to exclude the mp3 directory from our search path.
One more way to exclude a directory is to use the ! operator with the find command:
$ find . -type f ! -path '*/txt/*'
./jpeg/3.jpeg
./jpeg/2.jpeg
./jpeg/1.jpeg
./mp3/1.mp3
./mp3/2.mp3
./mp3/3.mp3
In the above example, we’re using the ! operator to exclude the txt directory.
In this tutorial, we discussed three practical examples to exclude directories from the find command’s search path. We can use these commands in day-to-day life while working with the Linux system.