How to Find Files by Name in Linux

The locate command in Linux is used to quickly find files and directories by searching a pre-built index. It is much faster than find but requires the updatedb command to refresh the index.

Alby Andersen

The locate command in Linux is used to quickly find files and directories by searching a pre-built database of file paths. It’s faster than find but requires the database to be updated regularly using the updatedb command. Below are practical examples to master locate:


Search for a File by Name

locate file.txt  


Finds all files named file.txt in the database.


Search for Files with a Specific Extension

locate "*.log"  


Finds all files with the .log extension.


Limit the Number of Results

locate -n 10 file.txt  
  • -n 10: Displays only the first 10 results.

Ignore Case Sensitivity

locate -i File.TXT  
  • -i: Performs a case-insensitive search.

Count the Number of Matching Files

locate -c file.txt  
  • -c: Displays the count of matching files instead of listing them.

Update the Locate Database

sudo updatedb  


Updates the database used by locate to include new files.


Search for Files in a Specific Directory

locate /var/log/*.log  


Finds .log files only in the /var/log directory.


locate -e --regex '^/home/(?!user1).*'  
  • -e: Excludes paths matching the regex (e.g., excludes /home/user1).

Display Only Existing Files

locate -e file.txt  
  • -e: Filters out paths that no longer exist.

Search for Files Modified in the Last 24 Hours

locate -c --regex '.*' | xargs -I {} find {} -mtime -1  
  • Combines locate with find to filter files modified in the last 24 hours.

Search for Files Owned by a Specific User

locate -r '^/home/user1/.*' | xargs -I {} ls -l {}  
  • Uses locate and ls to find and list files owned by user1.

Search for Files with a Specific Pattern

locate -r '/var/log/.*\.log$'  
  • -r: Uses regex to match .log files in /var/log.

Display the Database Paths

locate -S  
  • -S: Shows statistics about the locate database (e.g., paths, file count).

Search for Files with Spaces in Their Names

locate "*my file*"  


Finds files with spaces in their names (e.g., my file.txt).


Key Notes:

  • Database Updates: Run sudo updatedb regularly to keep the database current.
  • Speed: locate is faster than find but may not reflect recent changes.
  • Limitations: locate cannot search file contents or metadata (use find for advanced searches).
Share This Article