find

Updated on 21 Jun 2020

find is a command line tool that is very useful for searching for files and directories using some basic filtering conditions.

Options

Option Meaning
-name name of file for search
-iname case insensitive name of file/directory for search
-maxdepth maximum number of sub-directories to search
-mtime modification time - based on days
-type search only files (f) or directories (d).
-perm file/folder permissions
-size files that are greater or less than a certain size
-user files that are owned by a particular user
-exec execute a shell command for each file/folder found
-empty files or folders that are empty

Example 1

Here is a basic example of searching within the home/brent directory (and sub-directories) for *.log (the * is a wildcard).

  • Use -iname if you are not concerned about case in your search.
find /home/brent -name "*.log"

Example 2

We may have found the previous example returned too many results, so lets use -maxdepth to limit the number of sub-directories to search thru.

find /home/brent -maxdepth 2  -name "*.log"

Example 3

We can even find files based on their contents. This example searches all .txt in the home/brent directory up to a maximum 2 sub-directories deep. I have specified that the object is a file (-type f) and then run the command grep "TODO" for every file that meets the condition. Other notes:

  • The files that match are printed on the screen (-print).
  • The curly braces ({}) are a placeholder for the find match results. The {} are enclosed in single quotes (') to avoid handing grep a malformed file name.
  • The -exec command is terminated with a semicolon (;), which is escaped (\;) to avoid interpretation by the shell.
find /home/brent -maxdepth 2 -name "*.txt" -type f -exec grep "TODO" '{}' \; -print

Example 4

In this example we’ll look at searching for *.txt files that are less than 10k based on size.

  • replace -10k with +10k to find files larger than 10k.
  • can use -size twice to search for file sizes between 2 values.
find /home/brent -maxdepth 2 -name "*.txt" -size -10k

Example 5

In this example we’ll see if we can find any empty files or directories.

  • I can specify -type to limit my search to only files or directories
find /home/brent -maxdepth 1 -empty