Skip to content

File Searching and Finding (find, locate, which)

Category: Linux Command Basics
Type: Linux Commands
Generated on: 2025-07-10 03:05:39
For: System Administration, Development & Technical Interviews


File Searching and Finding (find, locate, which) - Linux Cheatsheet

Section titled “File Searching and Finding (find, locate, which) - Linux Cheatsheet”

This cheatsheet provides a comprehensive guide to using find, locate, and which commands for locating files and directories in Linux. It’s designed for both beginners and experienced sysadmins and developers.

1. Command Overview

  • find: Recursively searches the directory tree for files matching specific criteria (name, size, modification time, etc.). Extremely powerful and flexible, but can be slow on large file systems. Best for precise searches with complex criteria.

  • locate: Uses a pre-built database (usually updated daily) to quickly find files by name. Much faster than find, but may not be up-to-date if files have been recently created or moved. Best for quick searches by filename when accuracy isn’t critical.

  • which: Locates the executable files associated with commands. Useful for determining which version of a command is being used (e.g., if multiple versions are installed). Best for finding the full path of a command.

2. Basic Syntax

  • find [path] [expression]

    • path: The directory to start the search (defaults to current directory if omitted).
    • expression: The criteria used to match files.
  • locate [options] pattern

    • pattern: The filename or pattern to search for.
  • which [options] command

    • command: The name of the command to find.

3. Practical Examples

find Examples:

  • Find all files named myfile.txt in the current directory and its subdirectories:

    Terminal window
    find . -name myfile.txt

    Output (example):

    ./path/to/myfile.txt
    ./another/path/myfile.txt
  • Find all files ending with .log in the /var/log directory:

    Terminal window
    find /var/log -name "*.log"

    Output (example):

    /var/log/syslog
    /var/log/auth.log
    /var/log/kern.log
  • Find all directories named testdir under /home:

    Terminal window
    find /home -type d -name testdir

    Output (example):

    /home/user1/testdir
    /home/user2/testdir
  • Find all files larger than 10MB (10485760 bytes) in /tmp:

    Terminal window
    find /tmp -size +10M

    Output (example):

    /tmp/large_file.dat
    /tmp/another_large_file.iso

locate Examples:

  • Find all files containing “report” in their name:

    Terminal window
    locate report

    Output (example):

    /home/user/documents/monthly_report.pdf
    /var/log/apache2/access_report.log
  • Find all files containing “config” in their name, ignoring case:

    Terminal window
    locate -i config

    Output (example):

    /etc/nginx/nginx.conf
    /home/user/.config/nvim/init.vim

which Examples:

  • Find the full path to the python3 command:

    Terminal window
    which python3

    Output (example):

    /usr/bin/python3
  • Find all locations of the java command:

    Terminal window
    which -a java

    Output (example):

    /usr/bin/java
    /usr/lib/jvm/java-11-openjdk-amd64/bin/java

4. Common Options

find Options:

  • -name <pattern>: Find files matching the given filename pattern (supports wildcards).
  • -iname <pattern>: Case-insensitive version of -name.
  • -type <type>: Find files of a specific type (e.g., f for file, d for directory, l for symbolic link).
  • -size <+|-size>: Find files of a specific size. + for greater than, - for less than, no sign for exactly. Size can be specified in c (bytes), k (kilobytes), M (megabytes), G (gigabytes).
  • -mtime <+|-n>: Find files modified n days ago. + for older than n days, - for newer than n days.
  • -atime <+|-n>: Find files accessed n days ago.
  • -mmin <+|-n>: Find files modified n minutes ago.
  • -exec <command> {} \;: Execute a command on each found file. {} is replaced with the filename. The \; terminates the command. Warning: Use with caution, especially with destructive commands.
  • -ok <command> {} \;: Like -exec, but prompts for confirmation before executing the command. Safer than -exec.
  • -delete: Delete files that match the search criteria. Warning: Extremely dangerous. Double-check your criteria before using this.
  • -print0: Prints filenames separated by null characters, useful for piping to other commands that can handle null-separated input (e.g., xargs -0).
  • -path <pattern>: Matches the entire file path, not just the filename.
  • -regex <pattern>: Matches the entire file path using a regular expression.

locate Options:

  • -i: Case-insensitive search.
  • -n <limit>: Limit the number of results.
  • -c: Count the number of matching files.
  • -r <regex>: Use a regular expression for the search pattern.
  • -b: Match only the base name of the file (the filename without the directory path).
  • -d <database>: Specify an alternate database to use.

which Options:

  • -a: Print all matching executable files, not just the first one.
  • -v: Verbose output.
  • --skip-alias: ignore aliases
  • --skip-functions: ignore shell functions
  • --skip-userspace: ignore userspace executables
  • --all: Print all matching executable files, including aliases and functions. (same as -a)

5. Advanced Usage

find Advanced Examples:

  • Find files modified in the last 24 hours and execute chmod 644 on them:

    Terminal window
    find . -mtime -1 -type f -exec chmod 644 {} \;

    Safety Warning: This command will change permissions on all files found. Use -ok instead of -exec for confirmation:

    Terminal window
    find . -mtime -1 -type f -ok chmod 644 {} \;
  • Find all empty directories and delete them:

    Terminal window
    find . -type d -empty -delete

    Safety Warning: This command will permanently delete empty directories. Test it thoroughly before running it on a production system. Consider using -print first to see which directories will be deleted.

  • Find all files in /var/www/html that are owned by the www-data user and group and are world-readable, then remove world readability:

    Terminal window
    find /var/www/html -user www-data -group www-data -perm -002 -exec chmod o-r {} \;
  • Find files modified in the last hour and pipe them to xargs to compress them with gzip:

    Terminal window
    find . -mmin -60 -type f -print0 | xargs -0 gzip

locate Advanced Examples:

  • Find all files ending with .conf in /etc, using a regular expression:

    Terminal window
    locate -r "^/etc/.*\.conf$"

    Explanation:

    • ^: Matches the beginning of the string.
    • /etc/: Matches the /etc/ directory.
    • .*: Matches any character (.) zero or more times (*).
    • \.conf: Matches .conf literally (escaped dot).
    • $: Matches the end of the string.

6. Tips & Tricks

  • Updating the locate database: The locate command relies on a database. Update it regularly (usually done automatically by a cron job). To manually update the database, run:

    Terminal window
    sudo updatedb
  • Combining find with other commands: Use find -exec, find -ok, or piping with xargs to perform actions on the found files.

  • Using -print0 with xargs -0: This is a safe way to handle filenames with spaces or special characters.

  • Optimizing find performance: Avoid unnecessary recursion. Use more specific criteria to narrow down the search. Consider using locate if you only need to search by filename.

  • Using -quit with find: If you only need to find one matching file, you can use -quit to stop the search after the first match. This can significantly improve performance, especially on large filesystems. Example: find . -name "myfile.txt" -print -quit

7. Troubleshooting

  • locate not finding recently created files: The locate database needs to be updated. Run sudo updatedb.
  • find taking too long: Refine your search criteria. Start the search in a more specific directory.
  • Permission denied errors with find: You may not have permission to access some directories. Try running the command with sudo or specify a different starting directory.
  • Issues with -exec: Make sure the command you’re executing is valid and that the {} placeholder is correctly placed. Test the command on a single file first. Use -ok for safety.
  • **find: missing argument to \-exec`:** Ensure you properly terminate the -execcommand with;`.

8. Related Commands

  • grep: Searches within files for lines matching a pattern.
  • ls: Lists directory contents.
  • stat: Displays file or file system status.
  • file: Determines file type.
  • du: Estimates file space usage.
  • tree: Displays directory structure in a tree-like format.
  • fd: A simpler and faster alternative to find, written in Rust. (Requires installation).
  • ripgrep (rg): Very fast recursive search tool. (Requires installation)

This cheatsheet provides a foundation for using find, locate, and which. Experiment with different options and combinations to become proficient in locating files and directories in Linux. Remember to exercise caution when using commands that can modify or delete files.