How to use find command | LinuxGist
The find command in Linux is often referred to as a "Swiss Army Knife" because of its versatility and wide range of uses.
The find command in Linux is often referred to as a “Swiss Army Knife” because of its versatility and wide range of uses. It’s one of the most powerful commands available for searching, locating, and manipulating files and directories on a Unix-like operating system.
Here are some common use cases of the find command:
Basic Usage
The basic syntax of the find command is:
1
find <path> [expression]
<path>: The starting directory for the search.[expression]: Conditions or actions to perform on the files and directories.
Examples
- Find all
.txtfiles in a directory:1
find /path/to/search -name "*.txt"
- Find all files modified within the last 10 days:
1
find /path/to/search -mtime -10
- Find and delete all
.txtfiles:1
find /path/to/search -name "*.txt" -exec rm {} \;
- Find and rename all
.txtfiles to.bak:1
find /path/to/search -name "*.txt" -exec sh -c 'mv "$0" "${0%.txt}.bak"' {} \;
- Find directories that are not empty:
1
find /path/to/search -type d ! -empty
- Find files owned by a specific user:
1
find /path/to/search -user username - Find files with specific permissions (e.g., 644):
1
find /path/to/search -perm 644 - Find and print the size of all
.jpgfiles:1
find /path/to/search -name "*.jpg" -exec ls -lh {} \;
- Find and execute a command on each file:
1
find /path/to/search -name "*.log" -exec grep "error" {} +
- Find files that match multiple patterns (e.g.,
.jpgor.png):1
find /path/to/search \( -name "*.jpg" -o -name "*.png" \)
Advanced Usage
- Using
-execdir: Execute a command in the directory containing the file:1
find /path/to/search -type f -name "*.txt" -execdir rm {} \;
- Using
-delete: Delete files matching the expression:1
find /path/to/search -name "*.tmp" -delete
- Combining multiple conditions with
-a,-o, and!:1
find /path/to/search \( -type f -mtime +7 -o -size +100M \) ! -user username
- Using
-mindepthand-maxdepthto limit the search depth:1
find /path/to/search -mindepth 2 -maxdepth 3 -name "*.log"
Summary
The find command is incredibly versatile and can be used for a wide range of tasks, from simple file searches to complex directory manipulations. Its ability to combine multiple conditions and execute commands on matching files makes it a true “Swiss Army Knife” in the world of Unix-like command-line tools.