The Wayback Machine - https://web.archive.org/web/20240828110729/https://www.geeksforgeeks.org/locate-command-in-linux-with-examples/
Open In App

locate command in Linux with Examples

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

locate command in Linux is used to find the files by name. There are two most widely used file-searching utilities accessible to users called to find and locate. The locate utility works better and faster than the find command counterpart because instead of searching the file system when a file search is initiated, it would look through a database. This database contains bits and parts of files and their corresponding paths on your system. By default, locate command does not check whether the files found in the database still exist and it never reports files created after the most recent update of the relevant database.

Syntax of `locate` command in Linux 

locate [OPTION]... PATTERN...

Exit Status: This command will exit with status 0 if any specified match is found. If no match is found or a fatal error is encountered, then it will exit with status 1.

Options Available in `locate` command in Linux

OPTIONS

DESCRIPTION

-b, –basename

Match only the base name against the specified patterns, which is the opposite of –wholename.

-c, –count

Instead of writing file names on standard output, write the number of matching entries only.

-d, –database DBPAT

Replace the default database with DBPATH. DBPATH is a : (colon) separated list of database file names. If more than one –database option is specified, the resulting path is a concatenation of the separate paths. An empty database file name is replaced by the default database. A database file name – refers to the standard input. Note that a database can be read from the standard input only once.

-e, –existing

Print only entries that refer to files existing at the time locate is run.

-L, –follow

When checking whether files exist (if the –existing option is specified), follow trailing symbolic links. This causes bro ken symbolic links to be omitted from the output. This option is the default behavior. The opposite can be specified using –nofollow.

-h, –help

Write a summary of the available options to standard output and exit successfully.

-i, –ignore-case

Ignore case distinctions when matching patterns.

-l, –limit, -n LIMIT

Exit successfully after finding LIMIT entries. If the –count option is specified, the resulting count is also limited to LIMIT.

-m, –mmap

Ignored, but included for compatibility with BSD and GNU locate.

-P, –nofollow, -H

When checking whether files exist (if the –existing option is specified), do not follow trailing symbolic links. This causes broken symbolic links to be reported like other files. This option is the opposite of –follow.

-0, –null

Separate the entries on output using the ASCII NULL character instead of writing each entry on a separate line. This option is designed for interoperability with the –null option of GNU xargs.

-S, –statistics

Write statistics about each read database to standard output instead of searching for files and exit successfully.

q, –quiet

Write no messages about errors encountered while reading and processing databases.

-r, –regexp REGEXP

Search for a basic regexp REGEXP. No PATTERNs are allowed if this option is used, but this option can be specified multiple times.

–regex

Interpret all PATTERNs as extended regexps.

-s, –stdio

Ignored, for compatibility with BSD and GNU locate.

-V, –version

Write information about the version and license of locate on standard output and exit successfully.

-w, –wholename

Match only the whole path name against the specified patterns. This option is the default behavior. The opposite can be specified using –basename.

Search a File with Specific Name Using locate Command

locate sample.txt 

It will search for sample.txt in a particular directory.

336.webp

Limit Search Queries to a Specific Numbe Using locate Command

locate "*.html" -n 20

It will show 20 results for the searching of file ending with .html.

337.webp

Display The Number of Matching Entries Using locate Command

locate -c [.txt]*

It will count files ending with .txt.

338.webp

Ignore Case Sensitive Locate Outputs Using locate Command

This command is configured to process queries in a case sensitive manner. It means SAMPLE.TXT will show a different result than sample.txt.

$ locate -i *SAMPLE.txt*

339.webp

Separate Output Entries Without New Line Using locate Command

locate -i -0 *sample.txt*

Default separator for locate command is the newline (\\n) character. But if someone wants to use a different separator like the ASCII NULL, then he/she can do so using the -0 command line option.

340.webp

Conclusion

In this article we have discussed the `locate` command in Linux which is a valuable tool for quickly searching for files and directories. It uses a pre-built database which allows for fast and efficient searches, making it an ideal choice for locating files in a large file system. Overall, we can say that by mastering the `locate` command and its various options, we can save time and effort when searching for specific files or directories on our Linux system.

locate command in Linux with Examples – FAQs

What is the locate command used for in Linux?

The locate command in Linux is used to quickly find the locations of files on the system by querying a database that contains a snapshot of all the files in the system. It is much faster than find because it searches this pre-built database rather than the filesystem directly. This makes locate ideal for situations where you need quick results and the file system has not changed significantly since the last database update.

How to use locate to find files by name?

To find files by name using the locate command, simply provide the filename or pattern you want to search for. For example, to search for all occurrences of a file named example.txt, you would use:

locate example.txt

To search for all files that contain the word “example” in their name, you can use:

locate example

This will return a list of all files that have “example” anywhere in their filenames.

Can locate search for hidden files?

Yes, locate can search for hidden files as well. Hidden files (those beginning with a dot .) will be indexed and displayed by locate as long as they are present in the database it queries. For example, to find a hidden file named .bashrc, you could use:

locate .bashrc

How to update the database used by locate?

The database used by locate is updated periodically via a scheduled job run by cron or systemd on most systems. However, if you have newly added files that you need to find immediately, you may manually update the database by running:

sudo updatedb

This command refreshes the database that locate queries, ensuring that any recent files are included in subsequent searches.

What are some common options for the locate command?

locate includes several options to refine and control search results:

  • -i: Ignore case distinctions in both the pattern and the file names.
  • –regex: Treat the pattern as a regular expression, rather than as a plain string.
  • -n, –limit: Limit the number of search results returned. For example, locate -n 10 pattern will return only the first 10 matches.
  • -b, –basename: Match only the base name against the specified patterns. This excludes directory names and matches only the filenames.
  • -c, –count: Instead of displaying the file names, locate will display the number of matched entries only.


Previous Article
Next Article

Similar Reads

Difference between locate, which and find Command in Linux
There are a number of Linux utilities that can be used to locate files in a Linux installation with three of the most common being find, locate, and which. All three of these utilities have similar functions, but work and return data in different ways. In this article, we are going to discuss these three useful and powerful command-line utilities t
5 min read
Linux - Installing locate Command to Find Files
In this article, we will see how to install locate command to find files in Linux. locate is a command-line interface tool used for finding files by name in Linux systems. This works more efficiently than other commands. It uses one or more databases by updatedb. To check whether locate utility is already installed in your system. Open up your term
2 min read
Important Linux Commands (leave, diff, cal, ncal, locate and ln)
Linux provides some important tricks. Here are a few and important one's: leave — remind you when you have to leave Syntax: leave +hhmm leave waits until the specified time (within the next 12 hours), then reminds you that you have to leave by writing to the TTY that you executed leave on. You are reminded 5 minutes and 1 minute before the actual t
2 min read
Ccat – Colorize Cat Command Output command in Linux with Examples
ccat is a command-line tool for Linux and OSX, which is similar to the cat command in Linux. But the difference between cat and ccat is that the ccat shows the content of the file with the syntax highlighted. Currently, ccat supports the following programming languages. JavaScriptJavaRubyPythonGoCJSONInstallation of Ccat First, we are going to see
2 min read
How to Display Command History in Linux | history Command
The command-line interface in Linux provides powerful tools for users, and mastering command history is essential for efficient navigation and retrieval of previously executed commands. The history command is a valuable utility that allows users to view and search through their command history. In this comprehensive guide, we will explore the vario
4 min read
select command in Linux with examples
select command in Linux is used to create a numbered menu from which a user can select an option. If the user enters a valid option then it executes the set of command written in select block and then ask again to enter a number, if a wrong option is entered it does nothing. If user enters nothing and simply press 'enter' the option menu gets print
1 min read
atrm command in Linux with examples
atrm command is used to remove the specified jobs. To remove a job, its job number is passed in the command. A user can only delete jobs that belong to him. Only superuser can delete any job even if that belongs to another user. Syntax: atrm [-V] job [job...] Options: -V : Used to print the version number atrm -V job : Job number of the job which i
1 min read
comm command in Linux with examples
comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique. Suppose you have two lists of people and you are asked to find out the names available in one and not in the other, or even those common to both. comm is the command that will help you to achieve this. It requires two so
5 min read
cmp Command in Linux with examples
cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out whether the two files are identical or not. When cmp is used for comparison between two files, it reports the location of the first mismatch to the screen if difference is found and if no difference is found i.e the files compared are identical.cmp dis
5 min read
expand Command in LINUX with examples
Whenever you work with files in LINUX there can be a situation when you are stuck with a file containing many tabs and whatever you need to do with a file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you n
3 min read
df Command in Linux with examples
There might come a situation while using Linux when you want to know the amount of space consumed by a particular file system on your LINUX system or how much space is available on a particular file system. LINUX being command friendly provides a command line utility for this i.e df command that displays the amount of disk space available on the fi
8 min read
help Command in Linux with examples
If you are new to LINUX operating system and having trouble dealing with the command-line utilities provided by LINUX then you really need to know first of all about the help command which as its name says help you to learn about any built-in command. help command as told before just displays information about shell built-in commands. Here's the sy
3 min read
fgrep command in Linux with examples
The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as "^", "$", etc. Syntax: fgrep [options] [ -e pattern_list] [pattern] [file] Options with Description
3 min read
rcp Command in Linux with examples
There comes a time while using LINUX when there is a need to copy some information stored in a file to another computer. This can be done simply using rcp command line utility . Obviously there exists some other methods to complete the above mentioned task which are more secure (like scp or rsync) but this command lets you do this in the simple way
4 min read
fmt command in Linux with examples
fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time-consuming when it comes to large text files, this is where fmt comes to rescue. fmt re-formats each paragraph in the file specified, writing to standard output. Here's the syntax
4 min read
unexpand command in Linux with Examples
To convert the leading spaces and tabs into tabs, there exists a command line utility called unexpand command. The unexpand command by default convert each spaces into tabs writing the produced output to the standard output. Here's the syntax of unexpand command : Syntax : $unexpand [OPTION]... [FILE]... where, OPTION refers to the options compatib
2 min read
basename Command in Linux with examples
basename strips directory information and suffixes from file names i.e. it prints the file name NAME with any leading directory components removed. Using basename command : The basename command can be easily used by simply writing basename followed by the file name or the full pathname. Syntax of basename command : $basename NAME [SUFFIX] or $basen
3 min read
uniq command in Linux with examples
The linux uniq command is basically used to remove all repeated lines in a file. This command is used when a line is repeated multiple times and replace these multiple lines with one line. This command is designed to work on sorted files. Purpose : Remove repetitious lines from the sorted 'input-file' and send unique lines to the 'output-file'. If
2 min read
anacron command in linux with examples
anacron command is used to execute commands periodically with a frequency specified in days. Its main advantage over cron is that it can be used on a machine which is not running continuously. In cron if a machine is not running on time of a scheduled job then it will skip it, but anacron is a bit different as it first checks for timestamp of the j
3 min read
for command in Linux with Examples
for command in Linux is used to repeatedly execute a set of command for every element present in the list. Syntax: for NAME [in WORDS ... ] ; do COMMANDS; done Example: Options: help for : It displays help information.
1 min read
exit command in Linux with Examples
exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed. Syntax: exit [n] Options for exit command - exit: Exit Without Parameter After pressing enter, the
1 min read
autoheader command in Linux with Examples
autoheader command in Linux is used to create a template file of C "#define" or any other template header for configure to use. If the user will give autoheader an argument, it reads the standard input instead of reading configure.ac and also writes the header file to the standard output. This command scans the configure.ac file and figures out whi
1 min read
expect command in Linux with Examples
expect command or scripting language works with scripts that expect user inputs. It automates the task by providing inputs. // We can install expect command using following if not installed // On Ubuntu $sudo apt install expect // On Redhat based systems $ yum install expect First we write a script that will be needing inputs from users and then we
2 min read
cal command in Linux with Examples
If a user wants a quick view of the calendar in the Linux terminal, cal is the command for you. By default, the cal command shows the current month calendar as output. cal command is a calendar command in Linux which is used to see the calendar of a specific month or a whole year. Syntax: cal [ [ month ] year] The rectangular bracket means it is op
2 min read
function command in Linux with examples
The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the user's current shell session or saved in the shell
2 min read
fg command in Linux with examples
fg command in linux used to put a background job in foreground. Syntax: fg [job_spec] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this job if n
1 min read
bg command in Linux with Examples
bg command in linux is used to place foreground jobs in background. Syntax: bg [job_spec ...] job_spec may be: %n : Refer to job number n. %str : Refer to a job which was started by a command beginning with str. %?str : Refer to a job which was started by a command containing str. %% or %+ : Refer to the current job. fg and bg will operate on this
1 min read
Clear Command in Linux with Examples
clear is a standard Unix computer operating system command that is used to clear the terminal screen. This command first looks for a terminal type in the environment and after that, it figures out the terminfo database for how to clear the screen. And this command will ignore any command-line parameters that may be present. Also, the clear command
2 min read
Continue Command in Linux with examples
continue is a command which is used to skip the current iteration in for, while, and until loop. It is used in scripting languages and shell scripts to control the flow of executions. It takes one more parameter [N], if N is mentioned then it continues from the nth enclosing loop. The syntax for the `continue` command in Linuxcontinue or continue [
2 min read
hostid command in Linux with examples
hostid is a command in Linux that is used to display the Host's ID in hexadecimal format. It provides a quick and straightforward way to retrieve the host ID, allowing administrators to associate it with software licenses or perform system-specific operations. Syntax of `hostid` command in Linuxhostid [OPTION] Options provided by hostedhostid --hel
1 min read