More Linux find command examples

The Linux find command is used to locate files and directories based on a wide variety of criteria. I'll try to cover the most common find examples here.

Back to top

Basic find command examples

To find a file or directory named "foo" somewhere below your current directory use a find command like this:

find . -name foo

If the filename begins with "foo" but you can't remember the rest of it, you can use a wildcard character like this:

find . -name "foo*"

If you know you're trying to find a file (and not a directory) type this:

find . -type f -name "foo*"

Conversely, if you're looking for a directory and not a file type this:

find . -type d -name "foo*"
Back to top

Using find to search multiple directories

If you're looking for a file that begins with the characters "foo" in several directories (named "dir1", "dir2", and "dir3") type this:

find dir1 dir2 dir3 -type f -name "foo*"
Back to top

Time-based find command examples

To find a file that has been modified recently use the -mtime option. With this option you specify time in 24-hour periods. This is the shortest time span you can search with:

find . -mtime 0

And this should round up to one full 24 hour period:

find . -mtime 1

If you want to be more precise, and find a file or directory that has been modified since noon on August 1st you can use this series of commands:

touch 08011200 poop
find . -mnewer poop
rm poop

In that sequence I created a temporary file named "poop", and gave it a very specific time stamp of noon on August 1st. Then I told the find command to find anything below the current directory that had a modification time newer than that file. And then when you're done you don't need "poop" any more.

Although I keep showing modification time, you can do the same things with access time and creation time.

Back to top

Find something and then execute something

My favorite thing to do with the find command is to find one or more files and then do something to them with one command. Here's how I search every file in or below the "/tmp" directory, looking for a string in all the files named "find me":

find /tmp -type f -exec grep -il "find me" {} \;

This find command uses the grep command, and can be read as "Find all files in or below the '/tmp' directory and use a case-insensitive search to look for the string 'find me' in each of those files. If the string is found, print the file name."

You can do other things using the same find command syntax, such as running the ls command on each file, or even the vi command on those files (if you want to edit them). Here's an example of using it with the ls -l command:

find /tmp -type f -exec ls -l {} \;
Back to top

Much more

There's much, much more you can do with the find command, so I'll refer you to the find command man page for most of those.

Back to top

I've written about the find command several times before, and here are some links to those previous writings:

Back to top