DEV Community

Cover image for Find a File by Name with find
Labby for LabEx

Posted on Originally published at labex.io

Find a File by Name with find

Originally published on LabEx Blog.

You remember a filename but not the folder that holds it. On Linux, find can start at a chosen directory, descend into its subdirectories, and print the paths whose names match. It reports locations; it does not open or change the files it finds.

This LabEx video follows an old menu file from a cafe directory to the path that identifies it. You can recreate the example in a directory you own.

A LabEx terminal shows find locating menu-old.txt inside an archive directory

Create a small directory tree

Run these commands in a disposable directory:

mkdir -p ~/find-demo/cafe/archive
cd ~/find-demo/cafe
touch menu.txt notes.txt archive/menu-old.txt
find . -type f -name 'menu-old.txt'
Enter fullscreen mode Exit fullscreen mode

The output is:

./archive/menu-old.txt
Enter fullscreen mode Exit fullscreen mode

The dot means “start in the current directory.” find also walks into the archive subdirectory. -type f limits the result to regular files, and -name tests the filename. Keeping the filename in quotes prevents the shell from treating any wildcard characters in it as its own pattern.

Read the result as a path

The leading ./ says the path is relative to the folder where you ran the command. In this example, follow archive/menu-old.txt below the current cafe directory to reach the matching file.

find searches names and paths, not the text stored inside a file. Use grep when you need to search file contents instead. If you only want to list the current folder without descending into subdirectories, find . -maxdepth 1 -type f is one way to keep the search shallow. See the GNU find manual for the full set of tests and actions.

Try another filename

Search for the notes file from the same directory:

find . -type f -name 'notes.txt'
Enter fullscreen mode Exit fullscreen mode

This time the result is ./notes.txt, because the file is directly inside cafe. Change the quoted name to one that is absent to see the normal no-match result: find prints no path and leaves the directory unchanged.

For a broader hands-on introduction to moving around a Linux environment and working with files, try Quick Start with Linux on LabEx.

Top comments (0)