The locate
command in Linux is used to find the locations of files quickly. It searches through a database of file names and paths, which is usually updated periodically. This makes it much faster than commands like find
for locating files.
Initial Example
Using locate
to find files that contain the word “example”:
locate example
LOCATE Parameters
Parameter | Description |
---|---|
-0, --null | Use ASCII NUL as the separator instead of newline. |
-A, --all | Only print names matching all non-option arguments. |
-b, --basename | Match the pattern against the base name of files. |
-c, --count | Print the total number of matches instead of file names, unless --print is also present. |
-d path, --database=path | Search the specified file name databases instead of the default. |
-e, --existing | Only print names of files that currently exist. |
-E, --non-existing | Only print names of files that do not currently exist. |
--help | Display help information and exit. |
-i, --ignore-case | Ignore case distinctions in patterns and file names. |
-l N, --limit=N | Limit the number of matches to N. |
-L, --follow | Treat broken symbolic links as non-existing files (default behavior). |
--max-database-age D | Change the maximum age of the locate database before a warning is issued (default is 8 days). |
-m, --mmap | Accepted for compatibility with BSD locate, but does nothing. |
-P, -H, --nofollow | Treat broken symbolic links as existing files. |
-p, --print | Print search results when normally they wouldn’t due to --statistics or --count . |
-r, --regex | Interpret the pattern as a regular expression. |
--regextype R | Use the specified regular expression dialect R. |
-s, --stdio | Accepted for compatibility with BSD locate, but does nothing. |
-S, --statistics | Print statistics about each locate database and exit without searching. |
--version | Display version information and exit. |
-w, --wholename | Match against the entire file name as listed in the database (default behavior). |
Examples
1. Basic Usage
To find all files and directories that contain the word “document”:
locate document
2. Case-Insensitive Search
To perform a case-insensitive search, use the -i
option:
locate -i document
3. Limiting the Number of Results
To limit the number of results, use the -n
option followed by the number of results you want:
locate -n 5 document
4. Updating the Database
To ensure the locate database is up-to-date, use the updatedb
command:
sudo updatedb
5. Search by File Extension
To find all files with a specific extension (e.g., .txt
):
locate '*.txt'
6. Search for Exact Matches
To find files that exactly match a specific name, use the -r
option with a regular expression:
locate -r '^/etc/hosts$'
7. Excluding Specific Directories
To exclude specific directories from the search, use the -e
option:
locate -e /bin /usr