Find your files using the locate command on Linux

If you love doing things using the command-line interface(CLI) or automating stuff, you would love to know about the usage of the locate command. It helps to find files by their names. You may use different kinds of options as per your need. Here we are going to list some of the possible use cases.

Basic use

locate foo

This will try to match the name "foo" against the whole name of the file(this includes the path from the current directory). The pattern (in this case "foo") must match part of the whole file name your pattern. In case it contains metacharacters, it must match exactly. This is the default behavior and is specified using the -w option.

Matching pattern

If you do not exactly remember the name of the file but have some idea about the pattern of the name that you gave to this file, you can use this feature.

locate -r '$'

The above command will look for all files whose names end with "". You can use the -i option to ignore case will matching patterns and file names.

Count the match

You may use the -c option to count the total number of matches, instead of printing the matched file names.

locate -c '.py'

This will count the number of python files in your system.

Match the basename

The "base name" of a file is just the last component of the name of the file. For example, the base name of /var/log/apache2/error.log is error.log.

locate -b .log

This will list out all from the log files (those that have .log at the end of their file name).

Limit the results

In case you want to limit the results. This can be extremely useful when you are using the command inside a script or application and need to display limited entries.

locate -bl 2 .log

This will just print 2 results that include ".log" in their base name.

These were some of the cases where we thought you may use the command locate to save your time. The possibilities are endless. We aim to make your learning curve through Linux smooth. We have stuff on other commands that aim to make your experience through Linux more fun.

Till we meet again in another blog post, keep hacking !!!


Login to join the discussion

Thanks for the article, Abhyudai. I'm now confused. Where should I use find and where locate?

krishna | 8 months, 1 week ago | 1 Reply
2 0

If you're using the same searches frequently you may locate since it will be faster. It works by creating lookup tables pretty similar to how most search engines work.

abhi | 8 months, 1 week ago
0 0

Login to join the discussion