Sometimes, you create a file and forget wherein the directory structure you put it. Sometimes you don’t know the exact location of files created by the system, applications, or other users. In Linux, you have several powerful tools for finding the files you’re looking for.
The locate Command
The locate command quickly searches for any specified string in file names and paths stored in the mlocate database. This database must be updated regularly for the search to be effective. The results displayed may be restricted to files that users have permission to access or execute.
Syntax
The syntax of the locate command is:
# locate [options] {string}
If you encounter the below error while running the locate command:
locate: command not found
you may try installing the below package as per the choice of your distribution:
Distribution | Command |
---|---|
Debian | apt-get install mlocate |
Ubuntu | apt-get install mlocate |
Alpine | apk add mlocate |
Arch Linux | pacman -S mlocate |
Kali Linux | apt-get install mlocate |
CentOS | yum install mlocate |
Fedora | dnf install mlocate |
Raspbian | apt-get install mlocate |
locate Command Options
The locate command supports different options that enable you to make your search more effective. Some of the options are described in the table.
Option | Used To |
---|---|
-r | Search for file names using regular expressions. |
-c | Display only the number of matching entries found, rather than the file names. |
-e | Return only files that exist at the time of search. |
-i | Ignore the casing in file names or paths. |
-n {number of entries} | Return only the first few matches up to the specified number. |
locate Command Examples
1. To locate any file:
# locate file.txt
2. To match only the basename against the pattern:
# locate -b file.txt # locate --basename file.txt
3. To get the counts for matching entries:
# locate -c file.txt # locate --count file.txt
4. To replace the default database with the given:
# locate -d # locate --database
5. To print the entries that exist at the time when locate was fired:
# locate -e filename # locate --existing filename
6. To follow trailing symbolic links:
# locate -L text # locate --follow text
7. To get the locate help:
# locate -h # locate --help
8. To exit successfully after finding a specified number of entries:
# locate -l 10 text # locate -n 10 text # locate --limit 10 text
9. To avoid following symbolic links:
# locate -P text # locate --nofollow text # locate -H text
10. To separate the output entries by ASCI NULL character:
# locate -0 text # locate --null text
11. To get the statistics about the read database:
# locate -S text # locate --statistics text
12. To suppress any errors if occurred:
# locate -q text # locate --quiet text
13. To get the version info:
# locate -V # locate --version
14. To match the whole pathname:
# locate -w text # locate --wholename text