Searching for Files in the Shell (macOS)

What good are all the files in the file system if you can’t find them again? Exactly—none. That’s why this blog post is all about searching for files (and folders) using the shell. There are several commands available for this, but I’ll focus on find.

Open the Terminal and create a new subfolder named “shell” in your Documents directory, then navigate into that folder:

% mkdir ~/Documents/shell
% cd ~/Documents/shell

Next, create two directories and a text file:

% mkdir dir1 dir2
% touch example.txt

Now, check with the ls (list) command whether both folders and the file were created:

% ls
example.txt   dir1   dir2

Then navigate to your user directory:

% cd

From here, we start the search:

find . -name "dir*"

With this command, files or folders whose names contain the string “dir” are searched. The dot stands for the current directory we are in. From there, find searches the corresponding subfolders. As a result, among other things, the folders created earlier should be displayed:

./Documents/shell/dir1  
./Documents/shell/dir2

Instead of a dot, I could also have specified the absolute path:

find /Users/bodo -name "dir*"

Next, we want to search for files with the file extension “txt”. To do so, we first change to the “Documents” directory:

% cd Documents

The search is performed with the following command:

% find . -name "*.txt"

Among the results, the file “example.txt” created earlier should be shown:

./shell/example.txt

Now you know the basics of searching for files and folders in the shell. The find command is extremely powerful. You should definitely take a look at the man page for find:

% man find

By the way, you can also perform a Spotlight search via the shell. The command for that is: mdfind.

This blog post is an excerpt from the book “macOS Shell for Beginners”. The book is available in its 4th edition on Amazon (for Kindle).