What is locate
?
The locate
command is a fast file search tool that uses a pre-built database of file names and paths to quickly find matches, unlike find
which searches the file system live.
Install locate
(Red Hat / RHEL)
sudo dnf install mlocate
Then update the file database:
sudo updatedb
How locate
Works
- It searches a database (usually
/var/lib/mlocate/mlocate.db
) that contains absolute paths of all files and directories. - This database is not updated in real-time—you must run
updatedb
manually or via cron for fresh entries.
Basic Usage
Find a File by Name
locate filename.txt
Output:
/home/user/docs/filename.txt
/var/tmp/cache/filename.txt
Find All Instances of a Command
locate ls
Shows all paths with “ls” in their names.
Filtering with grep
or --regex
Using grep
to Filter
locate log | grep apache
Shows paths with both “log” and “apache”.
Using --regex
for Regular Expression Matching
locate --regex '^/etc/.*\.conf$'
Explanation:
^/etc/
: starts with/etc/
.*
: any characters\.conf$
: ends with.conf
Output:
/etc/httpd/httpd.conf
/etc/ssh/sshd_config
Match a Specific File Extension
locate --regex '\.log$'
Finds all files ending with .log
.
Match File Names Containing Digits
locate --regex '/[a-zA-Z0-9_-]*[0-9]+.*\.txt$'
Finds .txt
files with digits in the name.
Match Hidden Files in Home Directory
locate --regex '^/home/[^/]+/\..*'
Explanation:
^/home/
: must start in/home/
[^/]+
: matches username folder/\.
: matches dotfiles.*
: any characters
Refreshing the Database
Use updatedb
when new files are added:
sudo updatedb
This updates /var/lib/mlocate/mlocate.db
.
Permissions Note
locate
may show results you don’t have permission to access. For privacy, RHEL may configure mlocate
to only show files accessible by the current user.
Advantages vs find
Feature | locate | find |
---|---|---|
Speed | Very fast | Slower (live scan) |
Real-time | No | Yes |
Regex support | Yes (--regex ) | Yes (-regex ) |
Needs DB? | Yes (updatedb ) | No |
Examples Summary
Task | Command | |
---|---|---|
Find all .log files | locate --regex '\.log$' | |
Find files in /etc/ ending in .conf | locate --regex '^/etc/.*\.conf$' | |
Find hidden files in user home | locate --regex '^/home/[^/]+/\..*' | |
Find names with digits | locate --regex '.*[0-9]+.*' | |
Find files with error in path | locate error or `locate | grep error` |
Last updated on