Commonly Used find Command in Linux/Shell Scripts

1. Introduction to the find Command

The find command is a powerful file search tool in Linux/Unix systems that can recursively traverse specified directories, search for files based on various conditions, and perform operations on them.

2. Format of the find Command

find [path] [options] [action]

3. Common Options and Examples of the find Command

(1) -name, search for files by name

Example: Find files starting with ‘a’ in the /home directory

find /home -name “a*”

(2) -iname, search for files by name, case insensitive

Example: Find files starting with ‘a’ or ‘A’ in the /home directory

find /home -iname “a*”

(3) -type, search by file type, f: file, d: directory, l: link

Example: Find all directories in the current directory

find . -type d

(4) -mtime +/-n, search by modification time (days), +n is n days ago, -n is within n days

Example: Find files modified more than 7 days ago in the /home directory

find /home -mtime +7

(5) -mmin +/-n, search by modification time (minutes), +n is n minutes ago, -n is within n minutes

Example: Find files modified within the last 5 minutes in the /home directory

find /home -mmin -5

(6) -size +/-n[unit], search by file size, +n is greater than n, -n is less than n, unit indicates the unit, possible values: c (bytes), k (KB), M (MB), G (GB)

Example: Find files larger than 100MB in the /home directory

find /home -size +100M

(7) -exec command {} \;, perform operations on the search results, this command is often used in shell scripts to execute a command on the found files, {} represents the found file, \; indicates the end of the command.

Example: Find files starting with ‘a’ in the /home directory and delete them

find /home -name “a*” -exec rm {} \;

Note: For safety, it is recommended to first execute the ls command to check and confirm the files to be deleted, such as:

find /home -name “a*” -exec ls {} \;

4. Practical Example Operations

Find files containing specific content

Example: Find all txt files in the current directory and subdirectories that contain the statement ‘pass test’

find . -name “*.txt” -exec grep -l “pass test” {} \;

Or

find . -name “*.txt” | xargs grep -l “pass test”

Leave a Comment