The find
command is a handy tool for searching files and directories based on various conditions. It’s incredibly powerful and flexible, allowing you to search through directories recursively, apply filters, and perform actions on the search results.
Initial Example
Using find
to search for a file named example.txt
in the current directory and its subdirectories:
find . -name "example.txt"
FIND Parameters
Parameter | Description |
---|---|
-name | Search for files and directories by name. |
-type | Specify the type of file to search for (f for files, d for directories). |
-size | Search for files based on their size (e.g., +100M for files larger than 100MB). |
-mtime | Find files modified within a certain number of days (e.g., -7 for the last 7 days). |
-exec | Execute a command on each file that matches the criteria. |
-perm | Search for files with specific permissions (e.g., 755 ). |
-user | Find files owned by a specific user. |
-group | Find files owned by a specific group. |
-iname | Case-insensitive search for files and directories by name. |
-maxdepth | Limit the search to a specified number of directory levels. |
-mindepth | Set the minimum number of directory levels to search. |
-empty | Search for empty files and directories. |
-path | Search for files and directories matching a specific path pattern. |
-prune | Exclude directories from the search, preventing further recursion into them. |
-ls | List the details of each file found, similar to ls -l . |
-delete | Delete the files that match the search criteria. |
Examples
1. Search by Name
To find files by their name:
find /path/to/search -name "filename"
2. Search by Type
To search for files (f
) or directories (d
):
find /path/to/search -type f -name "filename" find /path/to/search -type d -name "dirname"
3. Search by Size
To find files larger or smaller than a specific size (e.g., 100MB):
find /path/to/search -size +100M find /path/to/search -size -100M
4. Search by Modification Time
To find files modified within the last 7 days:
find /path/to/search -mtime -7
5. Execute Commands on Search Results
To execute a command on each file found, use the -exec
option:
find /path/to/search -name "filename" -exec rm {} \;
6. Search by Permissions
To find files with specific permissions (e.g., 755):
find /path/to/search -perm 755
7. Search by User or Group
To find files owned by a specific user or group:
find /path/to/search -user username find /path/to/search -group groupname