How to Use the Locate Command in Linux

Updated on November 1, 2024
How to Use the Locate Command in Linux header image

Introduction

The locate command in Linux is an alternative to the find command. Unlike find, the locate command looks for files in a regularly updated database in the system instead of searching the entire file system. This approach makes searching faster and convenient, especially when working with many files.

This article explains how to use the locate command to effectively search for files and directories in Linux.

Advantages of locate Over find Command

While both find and locate commands have their use cases, locate operates much faster. locate uses a database that Linux builds automatically in the background to allow for faster results. The results from locate may not always reflect the state of the system if the database is out of date. However, you can regularly update the database manually or schedule a cron job.

Alternatively, the find command in Linux provides more precise results by searching in real-time, making it ideal for locating files based on specific criteria.

Understand the locate Database

The locate command relies on a database that indexes file locations across your file system. By default, Linux updates this database periodically via a background job. However, it's important to update the database manually in case you make changes to the file system.

Update the Database Manually

You can manually trigger the system to update the locate database using the following command.

console
$ sudo updatedb

The above command ensures the system indexes the most recent files and directories.

Find the locate Database

By default, you'll find the locate database in the following location on most Linux systems.

/var/lib/mlocate/mlocate.db

However, you can specify a different database file when searching by passing the -d option:

console
$ locate -d /path/to/other/db pattern

The above command allows you to specify custom databases, especially when working on multiple mounted filesystems or network shares.

Install locate Command

Most Linux systems pre-install the locate command by default. However, if you don't find the command, follow the steps below to install it.

  1. Check whether the locate command is installed.

    console
    $ locate
    

    If locate is not installed, the command prints the following output.

    locate: command not found

Install locate on Ubuntu and Debian

Follow the steps below to install locate on Ubuntu and Debian.

  1. Update your system's package information index.

    console
    $ sudo apt update
    
  2. Install the locate package.

    console
    $ sudo apt install plocate
    

    The above command installs the plocate package, which provides the locate command on Ubuntu and Debian systems.

Install locate on CentOS and Fedora

Follow the steps below to install locate on CentOS and Fedora.

  1. Update your system's package information index.

    console
    $ sudo yum -y update
    
  2. Install the locate package.

    console
    $ sudo yum install mlocate
    

    This command installs the mlocate package, which provides the locate command on CentOS and Fedora systems.

To securely transfer files between local and remote systems, explore the scp command in Linux for efficient file management.

The locate Command Syntax

The following is a basic locate command syntax:

locate [options] pattern

In the above locate command:

  • [options]: Defines optional flags that modify the command's behavior.
  • pattern: Specifies the file or directory name to search for.

Set up Example Files and Directories

Follow the steps below to create sample files and directories to test the locate command.

  1. Create three empty .txt files.

    console
    $ touch vultr.txt Vultr.txt VULTR.txt
    
  2. Create two empty .exe files.

    console
    $ touch VULTR.exe file.exe
    
  3. Create a dir directory and a subdirectory. Replace /path/to/parent/ with your actual path.

    console
    $ mkdir -p dir /path/to/parent/dir1/sub_dir
    

    The above command creates the dir directory and sub_dir subdirectory under /path/to/parent/dir1/. The -p option creates parent directories if they don't exist.

    Find your active working directory.

    console
    $ pwd
    

    This command displays the full path of your working directory.

  4. Create a file like logfile.txt and write some sample data with a text editor such as Nano.

    console
    $ nano logfile.txt
    
  5. Add the following contents to the logfile.txt file.

    2024-09-01 09:00:00 ERROR User login failed
    2024-09-01 10:00:00 INFO User profile updated
    2024-09-01 11:00:00 ERROR Database connection error
    2024-09-01 12:00:00 ERROR User login failed
    2024-09-01 13:00:00 WARN Disk space low
    2024-09-01 14:00:00 ERROR User login failed

    Save and close the file.

Most Common locate Options

Here are the most common locate command options in Linux.

Option Description
-i Ignore case distinctions
-c Print only the count of matching file names
-n N Limit the number of results to N
-r Use basic regular expressions for pattern matching
--existing Print only existing files (ignore deleted files)
--regex Interpret pattern as an extended regular expression
-d Specify the database to use
--basename Match only the base file name
--wholename Match the whole file name

Run Practical locate Command in Linux Examples

Run the following samples to learn how to use the linux locate command.

  1. Update the locate database to index any new files and directories.

    console
    $ sudo updatedb
    
  2. Search for a specific file named vultr.txt.

    console
    $ locate vultr.txt
    

    This command lists all paths that match the vultr.txt filename and displays all instances from the database.

    Output:

    Locate vultr.txt file

  3. Perform a case-insensitive search for all files named vultr.txt.

    console
    $ locate -i vultr.txt
    

    This command performs a case-insensitive search, so it will return results for vultr.txt, Vultr.txt, and other case variations.

    Output.

    Case-Insensitive Search

  4. Count the number of files that match example.txt.

    console
    $ locate -c example.txt
    

    This command returns the total count of files that match example.txt, without listing them.

    Output.

    Count Matches

  5. Limit the search results to 10.

    console
    $ locate -n 10 example.txt
    

    This command limits the output to the first 10 matches for example.txt.

    Output.

    Limit Results

  6. Search for files that end with .exe using a regular expression.

    console
    $ locate -r '\.exe$'
    

    Output.

    Regular Expressions Search

Run Advanced locate Command Examples

Follow the steps below to run advanced locate command searches.

  1. Search for a directory named dir.

    console
    $ locate -r '/dir$'
    

    This command uses a regular expression to match directories matching dir at the end of the path.

    Output.

    Directory Search

  2. Search for all .pdf extension files.

    console
    $ locate -r '\.pdf$'
    

    This command finds all files with a .pdf extension at the end using a regular expression.

    Output.

    PDF Files Search

  3. Combine options to search for .log files, ignore cases, and limit the results to 5.

    console
    $ locate -ir '\.log$' -n 5
    

    This command performs a case-insensitive search for files that end with .log extension and limits the results to 5.

    Output.

    Combined Options

  4. Combine locate with awk to extract specific fields from the search results.

    console
    $ locate logfile.txt | xargs grep -i 'error' | awk '{$1=$2=$3=""; print substr($0, 4)}'
    

    This command finds the file path using locate, searches for error in that file with grep, and uses awk to remove the date, time, and log level from the output, displaying only the error messages.

    Output.

    Extract Fields with awk

  5. Combine locate with sort and uniq to count unique matches and sort them.

    console
    $ locate logfile.txt | xargs cat | grep -i 'error' | sort | uniq -c | sort -nr
    

    This command finds the file path using locate and displays its contents with cat. The command then searches for lines containing error using grep and sorts these lines alphabetically while counting the occurrences of each unique error message with uniq -c. The command then sorts the counts in descending order showing the most frequent errors at the top.

    Output.

    Sort and Count with uniq

  6. Combine locate with sed to perform inline editing on the search results.

    console
    $ locate logfile.txt | xargs cat | sed 's/error/ERROR/g'
    

    This command finds the file path using locate, displays its contents with cat, and replaces all occurrences of error with ERROR using sed. The command transforms the case of the error term throughout the file content.

    Output.

    Inline Editing with sed

  7. Combine locate with tee to save and display output simultaneously.

    console
    $ locate logfile.txt | xargs cat | grep 'ERROR' | tee output.txt
    

    This command finds the file path using locate, displays its contents with cat, searches for lines containing the term ERROR using grep, and writes the matching lines to the terminal and the output.txt file using tee.

    Output.

    Save and Display with tee

  8. Search files containing the word log and filter the results using the grep command.

    console
    $ locate log | grep '/var/log'
    

    The above command first finds all file names containing log and then pipes the output to grep to filter the results, showing only the files in the /var/log directory.

    Output.

    Filter with grep

  9. Delete all files that match vultr.txt by combining locate with xargs.

    console
    $ locate vultr.txt | xargs rm -f
    

    This command finds all files named vultr.txt and pipes the list to xargs, which then deletes the file using the rm -f command.

    Output.

    Delete locate file with xargs

  10. Use locate to search for files and run advanced actions using `find.

    console
    $ locate Vultr.txt | xargs -I {} find {} -type f -exec ls -l {} \;
    

    The above command finds all files named Vultr.txt and passes the list to find which executes ls -l on each file to display detailed information.

    Output.

    Combine locate with find

Set locate Command Environment Variables

The following Linux environment variables affect the locate command.

  • LOCATE_PATH: Specifies the path to the locate database.
  • LOCATE_CONFIG: Specifies the path to the locate configuration file.

The LOCATE_PATH Variable

This environment variable lets you define a custom path for the locate database. By default, locate searches through its pre-configured database, which is usually located in /var/lib/mlocate/mlocate.db.

You can set a different locate database path by running the following command. Then run locate to search for example.txt in that database.

console
$ export LOCATE_PATH='/var/lib/plocate/plocate.db'
$ locate example.txt

The LOCATE_CONFIG Variable

This environment variable specifies a custom configuration file path that determines how locate behaves. The default configuration file controls important parameters, such as which directories to exclude from the database or which files to ignore during the search. By customizing this file, you can fine-tune the locate command behavior to meet your specific needs.

While it's less commonly used compared to LOCATE_PATH, the LOCATE_CONFIG variable is useful when working in environments where the default configuration does not fit your requirements. You can point the variable to a custom configuration file that defines how the database is updated, which paths are indexed, and more.

You can set the LOCATE_CONFIG variable by running the following command.

console
$ export LOCATE_CONFIG='/path/to/my/locate.conf'

Use locate with mlocate and slocate Commands

mlocate and slocate commands are variants of the locate command but they offer additional features and security. These commands are often used interchangeably with locate.

The mlocate (Merging Locate) Command

mlocate is a variant of locate that only updates the parts of the database that have changed. This makes it faster and more efficient when updating the database, especially on systems with many files. mlocate sophisticated privacy features ensure users can only locate files they have permission to see.

Example of mlocate command.

console
$ sudo updatedb.mlocate
$ locate example.txt

The first command above updates the mlocate database and the subsequent locate command searches for example.txt in the database.

The slocate (Secure Locate) Command

slocate is another variant of locate that emphasizes on security. The command ensures that users can only see results for files they have the proper permissions to access. This is especially useful in multi-user environments where users shouldn't be able to locate files they don't have access to. slocate includes more advanced file permission checks when creating the database and searching files.

Example of slocate command.

console
$ sudo updatedb.slocate
$ locate example.txt

Just like in mlocate, the updatedb.slocate commad updates the database and then uses the locate command to perform your search. The key difference lies in the way the results are filtered based on user permissions, which may yield fewer results compared to a standard locate.

Conclusion

In this article, you've installed the locate command in Linux, covered the command's syntax, command options, and run practical examples. With the locate command, you can quickly and efficiently search for files and directories on your system. By utilizing the different locate command advanced use cases, you can enhance your search and streamline your workflow in Linux.