find
find is a command that recursively searches a directory tree to locate files. You can filter results by name, type, modification time, size, and more. It also has a powerful feature that lets you run a command on each file found.
Syntax
find starting-path [options] [conditions] [actions]
Options and Conditions
| Option / Condition | Description |
|---|---|
| -name "pattern" | Searches for files whose names match the pattern (wildcards are supported). |
| -iname "pattern" | Searches for files by name, case-insensitively. |
| -type f | Matches regular files only. |
| -type d | Matches directories only. |
| -type l | Matches symbolic links only. |
| -mtime n | Matches files modified n days ago. Use +n for "more than n days ago" and -n for "within the last n days". |
| -newer file | Matches files newer than the specified file. |
| -size n[cwbkMG] | Filters by file size (e.g., -size +1M matches files larger than 1 MB). |
| -maxdepth n | Limits the search to n levels deep. |
| -mindepth n | Skips entries shallower than n levels deep. |
| -empty | Matches empty files or directories. |
| -exec command {} \; | Runs the specified command on each matched file individually. |
| -exec command {} + | Passes all matched files to the command at once (more efficient). |
| -delete | Deletes each matched file. |
| ! condition | Negates the condition. |
Sample Code
The following examples use this directory structure.
Search for all .txt files under the current directory.
find . -name "*.txt" ./docs/readme.txt ./notes/todo.txt
List directories only.
find . -type d . ./.git ./docs ./src ./tmp ./notes
Search for files larger than 1 MB.
find . -type f -size +1M ./demo.mp4 ./archive.tar.gz
Search for files modified within the last 7 days.
find . -type f -mtime -7
Show detailed information for each found file using $ ls -lh.
find . -name "*.php" -exec ls -lh {} \;
-rw-r--r-- 1 user staff 4.2K Mar 5 10:00 ./src/app.php
-rw-r--r-- 1 user staff 1.8K Mar 5 09:30 ./src/helper.php
Delete all .tmp files.
find . -name "*.tmp" -delete ls tmp/
Search for .php files while excluding the .git directory.
find . -name ".git" -prune -o -name "*.php" -print ./src/app.php ./src/helper.php
List empty files.
find . -empty -type f
Limit the search depth. Search only the immediate contents of the current directory (1 level deep).
find . -maxdepth 1 -name "*.txt"
Notes
While '$ find' is extremely powerful, when conditions become complex, piping the results through '|' to xargs is often simpler than using '-exec'.
To search file contents for text, use '$ grep -r' instead of '$ find'. For listing files, also see ls.
If you find any errors or copyright issues, please contact us.