How to locate files and folders in Unix / Linux

In Unix and Linux systems, there are a few commands for finding files and folders. The most used are find and locate.

Watch Free Movies

In this article I will show you how to use locate properly, in order to find the files or dirs you need.

Locate uses a database (list) to search for files and folders. If your database needs to be updated, you will get this error message when using locate: locate: database too small

You can create a script that updates the locate database daily, or update it by hand, when needed:

How to update the database in Linux and Unix:

In Linux: $ sudo updatedb

In FreeBSD/PCBSD: # /usr/libexec/locate.updatedb

How to use locate:

Syntax:locate filename

I will locate the ssh_config file with locate:
$ locate ssh_config
/etc/ssh/ssh_config
/usr/share/man/man5/ssh_config.5.gz

Locate a dir and display the files inside it:

$ locate /etc/ssh
/etc/ssh
/etc/ssh/moduli
/etc/ssh/ssh_config
[...]

How to search for files and folders by the basename:
locate -b starwars will find only the files with the name “starwars” (case sensitive search)

$ locate -b starwars
/home/starwars

How to search for files and folders, ignoring the case type:

If i search for sample.txt, this locate command will find Sample.txt, SAMple.txt, SAMPLE.txt, sample.txt etc…

$ locate -i sample.txt
/home/razvan/sample.txt
/home/razvan/SAMPLE.txt
/home/razvan/samPLE.txt

How to limit locate’s output:
locate -l 3 will display only the first 3 lines, and locate -5 only the first 5:

$ locate -l 3 starwars
/home/starwars
/home/starwars/.bash_logout
/home/starwars/.config

$ locate -l 5 starwars
locate -l 5 starwars
/home/starwars
/home/starwars/.bash_logout
/home/starwars/.config
/home/starwars/.mozilla
/home/starwars/.profile

My locate bad habbit:
I got used to locate starwars | head -5 , but should use locate -l 5 starwars instead, because it’s shorter to type.

How to print numbers of entries find:
locate -c prints only the number of found results:

$ locate -c starwars
48

And finally, how to print database statistics with locate:

$ locate -S
Database /var/lib/mlocate/mlocate.db:
15,573 directories
150,422 files
7,703,618 bytes in file names
3,368,736 bytes used to store database

A good Unix user should know how to use the locate, find and whereis commands.

Scroll to Top