Exploring the "find" command

By Alvin J. Alexander, devdaily.com

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

Basic "find" examples

To find a file or directory named "foo" somewhere below your current directory type this:

find . -name foo

If the filename begins with "foo" but you can't remember the rest of it type this:

find . -name "foo*"

If you know you're looking for 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*"

Looking in 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*"

Time based finds

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 yo don't need "poop" any more.

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

Find something and do 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" {} \;

That command 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 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 {} \;

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.

Related examples

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


devdaily logo