Locating Files With find

The find command provides a wide range of capabilities for searching through directory trees, including executing commands on found files, searching for files based on creation and modification times, and more. It will search any set of directories you specify for files that match the criteria. For example, you might have thousands of files in your home directory and be looking for a file named foo:

$ pwd
/home/jolo

$ find . -name foo 
./foo

In the example above, the first argument "." indicates for find to start searching in the current directory (/home/jolo), and the flag -name with the argument foo means to search for a file named "foo". Find returns the relative path of the file "foo" when it finds it in the file system. In this case, the file was found right in the home directory.

You can also specify more than one location to search:

$ find /home/jolo/Project /home/jolo/Results/ . $HOME -name foo

This searches for the file name "foo" in the "/home/jolo/Project/", "/home/jolo/Results/", and the current directory.

Locating Files With locate

Another command provided on most Linux systems is the locate command, which builds a file-based database of files and their locations and will match strings. locate is usually faster than find because it searches the database, rather than looking in each directory and subdirectory. You can use locate myfile in order to find where the file is located. Try locate -h for a full list of options.

Pattern Matching With grep

The grep (global regular expression print) command is another useful utility that searches the named input file for lines that match the given pattern and prints those matching lines. In the following example, grep searches for instances of the word "bar" in the file "foo":

$ cat foo
tool
bar
cats
dogs

$ grep bar foo
bar

If there are no matches, grep will not print anything to the screen.

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement