Post

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

  1. Find all .txt files in a directory:
    1
    
    find /path/to/search -name "*.txt"
    
  2. Find all files modified within the last 10 days:
    1
    
    find /path/to/search -mtime -10
    
  3. Find and delete all .txt files:
    1
    
    find /path/to/search -name "*.txt" -exec rm {} \;
    
  4. Find and rename all .txt files to .bak:
    1
    
    find /path/to/search -name "*.txt" -exec sh -c 'mv "$0" "${0%.txt}.bak"' {} \;
    
  5. Find directories that are not empty:
    1
    
    find /path/to/search -type d ! -empty
    
  6. Find files owned by a specific user:
    1
    
    find /path/to/search -user username
    
  7. Find files with specific permissions (e.g., 644):
    1
    
    find /path/to/search -perm 644
    
  8. Find and print the size of all .jpg files:
    1
    
    find /path/to/search -name "*.jpg" -exec ls -lh {} \;
    
  9. Find and execute a command on each file:
    1
    
    find /path/to/search -name "*.log" -exec grep "error" {} +
    
  10. Find files that match multiple patterns (e.g., .jpg or .png):
    1
    
    find /path/to/search \( -name "*.jpg" -o -name "*.png" \)
    

Advanced Usage

  1. Using -execdir: Execute a command in the directory containing the file:
    1
    
    find /path/to/search -type f -name "*.txt" -execdir rm {} \;
    
  2. Using -delete: Delete files matching the expression:
    1
    
    find /path/to/search -name "*.tmp" -delete
    
  3. Combining multiple conditions with -a, -o, and !:
    1
    
    find /path/to/search \( -type f -mtime +7 -o -size +100M \) ! -user username
    
  4. Using -mindepth and -maxdepth to 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.

This post is licensed under CC BY 4.0 by the author.