How to find a file in linux

In *nix, you can use the find command to find a file easily.

$find {directory-name} -name {filename}

1. Find a file in the root directory
If you have no idea where the file is located, you can search the entire system via the “/” root directory. Below example shows you how to find a file, named testing.txt in the entire system drive.

P.S To find in “/” root, you need permission, just issue sudo.


$ sudo find / -name 'testing.txt'

find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/Users/mkyong/Documents/workspace/JavaTesting/testing.txt
/Users/mkyong/testing.txt

2. Find files in a specified directory
Find file testing.txt in directory /Users/mkyong and all its subdirectory..


$ sudo find /Users/mkyong -name 'testing.txt'
/Users/mkyong/Documents/workspace/JavaTesting/testing.txt
/Users/mkyong/testing.txt

4 comments on “How to find a file in linux

  1. find can do a lot more than merely print files.

    find . -name 
    find . -exec grep -Hi "text" {} \;
    find. -ctime (can't remember parameters off the top of my head)
    etc.
    
    Reply
  2. locate is a better choice sometimes — you run updatedb via root cron to create a hashed db of all files on the box. Then to find a file – “locate file.name or part-of-file-name” and you can pipe the results into a filter — for example a file name in a bin dir –
    “locate file.name | grep bin” or maybe list hits via ls -l for greater detail – “ls -l `locate file.name | grep bin` . find is a more cpu intensive utility – locate uses find too — but the hashed db may be accessed by many users rather than a separate find for each search.

    Reply
    1. locate myfile | ls -l fails because locate outputs a list of LF-terminated file names.
      How do we strip-out the LF’s so this will work? Something like:
      locate myfile | stripLF | ls -l would be fine if there were such a thing.
      (is there?)

      Reply
      1. It seems that you can do it with #locate myfile | xargs ls -l

        Reply

Leave a Comment

Your email address will not be published. Required fields are marked *