The locate
command is incredibly fast because it searches through a pre-built database of your filesystem rather than scanning directories in real-time. By default, it searches the entire filesystem, which can sometimes return too many irrelevant results.
The simplest way to constrain your search is to pipe locate's output through grep:
locate searchterm | grep "^/path/to/directory"
For example, to find all Python files in your /home/user/projects directory:
locate "*.py" | grep "^/home/user/projects"
For more precise control, consider using find
when you need to search within a specific directory:
find /path/to/directory -name "filename"
This searches in real-time rather than using a database, so it's slower but always up-to-date.
If you're not seeing recently created files, remember to update the locate database:
sudo updatedb
For complex searches, you can combine locate with regular expressions:
locate -r "^/var/www/.*\.conf$"
This finds all .conf files specifically in /var/www and its subdirectories.
While the grep method works well, for frequently searched directories, consider adding them to the PRUNEPATHS in /etc/updatedb.conf to exclude other locations from the locate database entirely.
The locate
command in Linux searches the entire filesystem by default because it queries a pre-built database of all files (usually updated daily via updatedb
). This makes searching extremely fast but sometimes too broad.
The most straightforward approach is to pipe locate
output to grep
:
locate "search_pattern" | grep "^/path/to/directory"
For example, to find all Python files in /home/user/projects:
locate "*.py" | grep "^/home/user/projects"
Some locate
implementations support regex (check with locate --help
):
locate --regex "^/var/log/.*\.log$"
For frequent searches in specific directories, modify /etc/updatedb.conf
to exclude paths:
PRUNEPATHS="/tmp /var/spool /media /home/*/.cache"
PRUNEFS="NFS nfs afs smbfs autofs"
Then update the database:
sudo updatedb
For current directory searches without database dependency:
find /specific/directory -name "pattern"
Example searching for config files in /etc:
find /etc -name "*.conf"
The locate
+grep
method works best when:
- The directory path is deep in the filesystem
- You need to search frequently
- The locate database is recently updated
For one-time searches in shallow directories, find
might be faster.
For system administrators managing specific directories:
sudo updatedb --localpaths='/path1 /path2' --output=custom.db
locate -d custom.db "search_term"