How to Use locate Command to Find Files in Linux:10 Example

From this blog you will Learn how to use the locate command in Linux to find files and directories quickly and easily, with 10 real-world examples.

  • locate passwd
    • Search for files with “passwd” in the name or path
  • Useful options
    • -i performs a case-insesitive search
    • -n x lists only the first x matches

Using an exact string as your locate argument will query the database and return all files that have the target string in their names. However, realize that when a database entry is made for a file, the filename is stored as the absolute path. Which means that if you were to perform a search like locate images; not only will you get files that are named images, or have images in their name, but also any named my_family_images or boot.images, but also any file that has images on it’s directory path such as

/usr/share/backgrounds/images/space or /usr/share/gimp/2.0/help/images/dialogs/dialogs-icon-floating.png

When using regular expressions with locate, remember to quote the regular expression as many regular expressions use shell meta characters. Also, locate only accepts basic regular expressions not extended regular expressions.

If you decide to use -n number to limit the number of results printed by locate, it will only print the first number results.

Here are 10 examples of how to use the locate command in Linux:

  1. Find all files with the name “myfile.txt”:
locate myfile.txt
  1. Find all files with the extension “.txt”:
locate *.txt
  1. Find all files in the current directory and its subdirectories:
locate .
  1. Find all files in the “/tmp” directory and its subdirectories:
locate /tmp
  1. Find all files that have been modified in the last 24 hours:
locate -mtime -1
  1. Find all files that are larger than 10 MB:
locate -size +10M
  1. Find all files that are owned by the user “root”:
locate -user root
  1. Find all files that have the permission “x” (executable):
locate -perm +x
  1. Find all files that contain the string “mystring”:
locate -i mystring
  1. Find all files that contain the regular expression “myregex”:
locate -r myregex

You can also combine these options to find files that meet multiple criteria. For example, to find all files with the name “myfile.txt” that are larger than 10 MB and have the permission “x”, you would use the following command:

locate myfile.txt -size +10M -perm +x

The locate command is a powerful tool for finding files in Linux. By using the examples above, you can learn how to use the locate command to find files based on name, size, date, owner, permissions, content, and more.

Leave a Comment