find
Command in Linux
Summary
The find
command is a powerful tool for locating files and directories within a file system. It allows you to search based on various criteria such as name, size, type, modification time, and permissions.
Introduction
The find
command is a fundamental utility in Linux for navigating and managing files. Unlike simply listing files, find
enables you to perform targeted searches based on specific attributes and then execute actions on the found items. This makes it invaluable for system administration, scripting, and general file management.
Use case and Examples
Find files by name
This command searches the current directory (.
) and its subdirectories for files named "myfile.txt". Find directories by name
This command searches the entire file system (/
) for directories (-type d
) named "mydir". Be cautious when searching the root directory, as it can take a significant amount of time. Find files modified in the last 7 days
This command searches the current directory and its subdirectories for files modified in the last 7 days.-mtime -7
means less than 7 days ago. Find files larger than 10MB
This command searches the current directory and its subdirectories for files larger than 10MB. The+
symbol indicates "greater than". Execute a command on found files
This command searches for all files ending with ".log" in the current directory and its subdirectories, and then executes therm
command (remove) on each found file. {}
is replaced with the filename, and \;
terminates the -exec
command. Be very careful when using -exec rm
to avoid accidental data loss. Commonly used flags
Flag | Description | Example |
---|---|---|
-name | Searches for files or directories by name (case-sensitive by default). | find . -name "myfile.txt" |
-iname | Searches for files or directories by name (case-insensitive). | find . -iname "myfile.txt" |
-type | Searches for files or directories of a specific type (e.g., f , d , l ). | find . -type d (finds directories) |
-size | Searches for files based on their size. | find . -size +10M (files larger than 10MB) |
-mtime | Searches for files modified within a specified number of days. | find . -mtime -7 (modified in the last 7 days) |
-atime | Searches for files accessed within a specified number of days. | find . -atime -30 (accessed in the last 30 days) |
-exec | Executes a command on the found files. | find . -name "*.txt" -exec rm {} \; |
-delete | Deletes the found files. Use with extreme caution. | find . -name "*.tmp" -delete |
-print | Prints the full path of the found files (default behavior). | find . -name "*.txt" -print |
-path | Searches based on the full path of the file | find / -path "*/node_modules/*" |
-not | ! | Negates a condition. Find files that don't match a criteria. | find . -not -name "*.txt" |