The find
command in Linux is a powerful tool for searching files and directories based on various criteria like name, size, type, and modification time. It’s essential for locating files, performing bulk operations, and automating tasks. Below are practical examples to master find
:
Contents
Find Files by NameFind Files by Name (Case-Insensitive)Find Files by TypeFind Files by SizeFind Files by Modification TimeFind Files by Access TimeFind Files by PermissionsFind and Delete FilesFind and Execute a Command on FilesFind Files and Print DetailsFind Empty Files or DirectoriesFind Files Owned by a Specific UserFind Files by Group OwnershipFind Files and Archive ThemFind Files and Copy Them to a DirectoryFind Files and Change Permissions
Find Files by Name
find /path/to/search -name "file.txt"
Searches for file.txt
in /path/to/search
.
Find Files by Name (Case-Insensitive)
find /path/to/search -iname "file.txt"
-iname
: Ignores case when matching names.
Find Files by Type
find /path/to/search -type f
-type f
: Finds only files.- Use
-type d
for directories.
Find Files by Size
find /path/to/search -size +100M
+100M
: Finds files larger than 100 MB.- Use
-100M
for files smaller than 100 MB.
Find Files by Modification Time
find /path/to/search -mtime -7
-mtime -7
: Finds files modified in the last 7 days.- Use
+7
for files modified more than 7 days ago.
Find Files by Access Time
find /path/to/search -atime -7
-atime -7
: Finds files accessed in the last 7 days.
Find Files by Permissions
find /path/to/search -perm 644
-perm 644
: Finds files with permissions set to644
.
Find and Delete Files
find /path/to/search -name "*.tmp" -delete
-delete
: Deletes files matching the pattern*.tmp
.
Find and Execute a Command on Files
find /path/to/search -name "*.log" -exec rm {} \;
-exec
: Executesrm
on each.log
file found.{}
: Represents the current file.
Find Files and Print Details
find /path/to/search -name "*.txt" -ls
-ls
: Displays detailed information about matching files.
Find Empty Files or Directories
find /path/to/search -empty
-empty
: Finds empty files or directories.
Find Files Owned by a Specific User
find /path/to/search -user username
-user
: Finds files owned byusername
.
Find Files by Group Ownership
find /path/to/search -group groupname
-group
: Finds files owned bygroupname
.
Find Files and Archive Them
find /path/to/search -name "*.log" -exec tar -czvf logs.tar.gz {} +
- Archives all
.log
files intologs.tar.gz
.
Find Files and Copy Them to a Directory
find /path/to/search -name "*.jpg" -exec cp {} /target/directory \;
- Copies all
.jpg
files to/target/directory
.
Find Files and Change Permissions
find /path/to/search -name "*.sh" -exec chmod 755 {} \;
- Changes permissions of
.sh
files to755
.
Key Notes:
- Recursive Search:
find
searches recursively by default. - Combining Conditions: Use
-and
,-or
, and-not
to combine search criteria. - Performance: For large directories, use
-maxdepth
to limit search depth.