15

I wanted to know, what is the best way to use the find command efficiently?

I generally use, find [filename] [dir] which gives me a long list of file names none of them any way related to my search.

I simply need to find one file in a particular directory. What is the command for that?

1 Answer 1

26

you usually tell find where to begin the search, and what to look for. So the syntax for paths to search and what you're actually trying to find is different.

For the use case you mention, let's assume you want to find the passwd file in /etc:

find /etc/ -name passwd

you're saying "starting in etc, look for a file whose name is passwd

if you don't specify criteria (or "options" in find parlance), what find does is, it starts in the path (or paths) you specify, and finds all files and directories underneath, recursively. So the options "filter" those files to narrow down what you're looking for.

Find all JPG files anywhere in your filesystem:

find / -name "*jpg" 

Using quotes in your options is recommended because otherwise shell expansion can cause you headaches.

Find any pdf files, regardless of case, in either Documents or Downloads:

find Documents/ Downloads/ -iname "*pdf"

If you do man find and scroll down to TESTS, you will find all the "criteria" that find can use to narrow down your search. You can search for files with specific filenames, owned by specific users or groups, having a specific file permission, being of a specific type (e.g. -type d will find only directories, while -type f will find only plain files, excluding directories), files newer or older than a specific number of days (or minutes), files that are empty, that are executable, and so on.

In find's man page you will also find a section called ACTIONS, these can go after the criteria and will be triggered by any file that matches all the criteria. So you can have find doing things like deleting files it finds, executing arbitrary commands on them, and so on.

But of course the basic syntax remains:

find [starting path(s)] [conditions or criteria]
2
  • thanks this works great. I was really confused and this helps set things straight
    – Sam007
    Jun 19, 2012 at 18:58
  • 1
    +1 This is a nice introduction to find, and also teaches the OP how to find further information.
    – lgarzo
    Jun 19, 2012 at 19:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .