locate Command Tutorial With Examples For Linux To Find Files
Linux have different tools to search and find files and directories.
locate is one of them which is very popular. The alternative for locate is
find command. But they work differently from each other. Find command searches in real time but locate command uses a database which holds all files and directories of the system. In this tutorial we will look how to use locate.
locate [OPTION]... PATTERN...
We can list help information about the
locate command with the
$ locate -h
As we stated in the introduction locate command uses a database to hold whole file system directories and files. This database is not updated automatically. So we should update database to use more effectively. As the there are some files requires root privileges to read and update database we should provide root privileges for the
$ sudo updatedb
Generally this update operation is not take too much time in periodic updated. But if the update runs for the first time this may some more times to setup database.
Search With Locate
Now we have updated our database we can search some terms. We will use
locate command the provide the search term. In the example we will search for
$ locate a.txt
As we can see from results the term
a.txt is not search for files it is simply looked in the full path string.
Display Only Existing Results
As we know locate command looks the database to find files and folders about search term. What if the database is updated one year ago and there is result those not exists any more. Locate command have the ability to double check if the result is exists currently. We will use
-e option to activate this feature.
$ locate -e a.txt
As we can see the first result
/home/ismail/a.txt not listed in the results because it is removed in the file system but the related record exits in the database. With
-e option we have corrected the result.
Some times there may be a lot of results which will fill our terminal. This is generally unwanted situation. There is an option which will limit the results count those will be printed to the terminal. We will use
-l option with the number. In the example we only want to list 5 results about search.
$ locate -l 5 a.txt
Display Only Result Count
Some times we only interested the count of results. This can be done various ways with helper commands. But locate command all ready provides option for this. We will use
-c option to only list the count of results.
￼$ locate -c a.txt
$ locate a.txt | wc -l
Display Statistics and Database Information
The database of locate will hold a lot of records. We can get information about this like statistics with
-S option. this will list directories count, files count, size of file names and total size of the database.
$ locate -S
The version of locate command can be displayed with
--version option like below.
$ locate --version