Introduction
The find
command on Ubuntu is a powerful tool for searching and locating files and directories within a file system. It allows you to search for files based on various criteria such as file name, file type, size, and modification time.
You can check find manual page at this link.
Basic Usage of find
The find
command allows you to search for files and directories within a specified path. Its syntax is straightforward:
find [path] [expression]
The path
is the directory you want to search in, and [expression]
defines how find
filters results. For instance:
Basic Examples of find command
This command searches for “myfile.txt” within the /home
directory:
find /home -name "myfile.txt"
Find files with a specific extension
find /path/to/search -name "*.log"
Using Filters and Options
find
supports various options for refined searches. The -name
option matches file names, while -type d
and -type f
search for directories and files, respectively. For example, to find all directories in /var
, use:
find /var -type d
You can also use find
with operators like -size
to find files of a specific size, -mtime
to filter by modification time, and -user
to search for files owned by a specific user. Here’s how to find files modified within the last two days:
find / -mtime -2
Combining Commands with -exec
The -exec
option lets you run a command on each file found. For example, to delete all .tmp
files:
find /tmp -name "*.tmp" -exec rm {} \;
Other usefull examples
Find files modified within the last N days:
find /path/to/search -mtime -7
Find and delete files:
find /path/to/search -name "obsolete_file.txt" -delete
Search for directories:
find /path/to/search -type d -name "directory_name"
Combine multiple criteria: This command finds all “.txt” files larger than 1 megabyte and displays detailed information using ls:
find /path/to/search -name "*.txt" -size +1M -exec ls -l {} \;
More articles with similar topic:
- Linux Files Operation: find Temp Files and Execute Commands on Found Files
- Find the Largest Files and Folders on Linux
- Solutions: Find and Delete Log Data or Any Files Older Than 30 Days on Linux