How To Find a File In Linux From the Command Line


Locate Linux Files by Their Name or Extension

Type find into the command line to track down a particular file by its name or extension. If you want to look for *.err files in the /home/username/ directory and all sub-directories, try this: 
 
find /home/username/ -name "*.err"

Typical Linux Find Commands and Syntax

find command expressions look like this:

find command options starting/path expression

Let’s break down a Linux find command where we don’t just want Linux find file by name:

find -O3 -L /var/www/ -name "*.html"

It enables the top-level optimization (-O3) and permits find to follow symbolic links (-L). The find command in Linux searches through the whole directory hierarchy under /var/www/ for files that have .html on the end.

Basic Examples

1. find . -name thisfile.txt

If you need to know how to find a file in Linux called thisfile.txt, it will look for it in current and sub-directories.

2. find /home -name *.jpg

Look for all .jpg files in the /home and directories below it.

3. find . -type f -empty

Look for an empty file inside the current directory.

4. find /home -user randomperson-mtime 6 -iname ".db"

Look for all .db files (ignoring text case) that have been changed in the preceding 6 days by a user called randomperson.

Options and Optimization for Find Command for Linux

find is configured to ignore symbolic links (shortcut files) by default. If you’d like the find command to follow and show symbolic links, just add the -L option to the command, as we did in this example.

find can help Linux find file by name. The Linux find command enhances its approach to filtering so that performance is optimised. The user can find a file in Linux by selecting three stages of optimisation-O1, -O2, and -O3. -O1 is the standard setting and it causes find to filter according to filename before it runs any other tests.

-O2 filters by name and type of file before carrying on with more demanding filters to find a file in Linux. Level -O3 reorders all tests according to their relative expense and how likely they are to succeed.

  • -O1 – (Default) filter based on file name first
  • -O2 – File name first, then file-type
  • -O3 – Allow find to automatically re-order the search based on efficient use of resources and likelihood of success
  • -maxdepth X – Search this directory along with all sub-directories to a level of X
  • -iname – Search while ignoring text case.
  • -not – Only produce results that don’t match the test case
  • -type f – Look for files
  • -type d – Look for directories

 



Article ID: 115
Created On: Sun, Jul 31, 2022 at 9:14 AM
Last Updated On: Sun, Jul 31, 2022 at 9:16 AM
Authored by: Saeed Nobakht [[email protected]]

Online URL: https://www.navel.ir/article/how-to-find-a-file-in-linux-from-the-command-line-115.html