Search This Blog

Find Command


The find command is used to recursively search a directory structure for files/directories that match specified criteria. Possible search criteria include name, modification date, file type, and many other possibilities. Once a matching file/directory has been found, it can be operated upon by copying it, deleting it, running wc or grep on it, etc. Typical uses of find include the following:
  • Recursively finding files with particular names
  • Doing recursive search & replace on files
  • Recursively deleting selected files
Find is a complex command with many options. Here we cover only a few of the most useful options. The find command-line has the following form:
$ find pathnames conditions operations
  • pathnames is a list of directories to search
  • conditions are the search criteria
  • operations are the operations to be performed on each matching file/directory

Search Criteria

The following examples show how to provide search criteria for several common types of searches.
  • Search by Name

    $ find pathnames -name pattern operations
    # print the paths of all files/dirs named core in the CWD
    $ find . -name core -print
    
    # print the paths of all .cpp files in cs240 directory
    $ find ~/cs240 -name '*.cpp' -print
    
  • Search by Type

    $ find pathnames -type c operations
    # print the paths of all regular files in the CWD
    $ find . -type f -print
    
    # print the paths of all directories in cs240 directory
    $ find ~/cs240 -type d -print
    
  • Search by Modification Time

    $ find pathnames -mtime (+n|-n|n) operations
    # print the paths of all files/dirs in the CWD that
    # were last modified more than 7 days ago
    $ find . -mtime +7 -print
    
    # print the paths of all files/dirs in the cs240
    # directory that were last modified less than 7 days ago
    $ find ~/cs240 -mtime -7 -print
    

Operations on Matching Files

The next examples show how to perform common operations on matching files/directories.
  • Print the full path of each matching file/directory

    $ find pathnames conditions -print
    # print the paths of all .cpp files in cs240 directory
    $ find ~/cs240 -name '*.cpp' -print
    
  • Execute a command on each matching file/directory

    $ find pathnames conditions -exec command {} \;
    # search all .cpp files in the CWD for "main"
    $ find . -name '*.cpp' -print -exec grep main {} \;
    
    # delete all .o files in the cs240 directory
    $ find ~/cs240 -name '*.o' -print -exec rm {} \;
    
    In this case, {} is replaced by the name of the matching file/directory, and \; is used to mark the end of the command.