Finding a file: find

To locate a file in the file system, use the find command.

  find pathname -name filename 

The pathname defines the directory to start from. Each subdirectory of this directory will be searched.

You can define the filename using wildcards. If these are used, the filename must be placed in 'quotes'.

Examples

To find a single file below the current directory:

   find . -name mtg_jan92 

This displays the pathname to the file mtg_jan92 starting from the current directory. If the file is not found nothing is displayed.

To find a file below your home directory:

   find ~/ -name README 

This displays the pathname to every file with the name README in your home directory or its subdirectories.

To find several files below the current directory:

   find . -name '*.fm' 

This displays the pathname to any file with the extension .fm which exists below the current directory.

To find a directory:

   find /usr/local -name gnu -type d 

This searches to see if there is a subdirectory gnu in the directory /usr/local.

Combining other commands with the find command

You can also use the find command to find a file and then carry out a command on that file. To do this use the command:

   find pathname -name filename  -exec command {}\;

To be prompted for confirmation before the command is executed use the command:

   find pathname -name filename -ok command {}\;

The command must be followed by a \ (backslash) and a ; (semi-colon). The {} (pair of braces) substitute the pathname of the file that is found as an argument to the command.

Examples

To remove several files:

   find . -name 'mtg_*' -exec rm {} \;

This will search for and remove all files starting with the expression mtg_ from the current directory and its subdirectories.

To find and remove specific files:

   find . -name '*.tmp' -ctime +30  -exec rm {} \;

This removes all files in the current directory and its subdirectories with the filename extension .tmp which have not been changed within the last 30 days.

To find and remove files interactively;

   find ~/Docs -name '*.ps' -ok rm {} \;

This searches for files with the extension .ps starting in the subdirectory "Docs" in the user's home directory. Each time a file is found that matches this expression, the user is prompted to confirm that they want to remove it.

Entering y removes the file.