How to Use the Linux find Command to Find Files

In this post we will look at the linux find command and how to search and find files with different attributes.

Linux find Command

The Linux find command is a built in powerful tool that can be used to locate and manage files and directories based on a wide range of search criteria.

For example, we can find files by their name, extension, size, permissions, etc. We can also use the find command to search for a particular text inside a file which we don’t know the name of.

Let’s see some usage of the find command with examples:

Searching for a file by name

If you know the name of a file but can’t remember the directory it’s in you can use the following command from the root directory:

find . -name sales.csv

Sample output:

./accounts/sales.csv

Searching for a specific file in a directory

If you want to search for specific file(s) in a directory, we can use:

find ./test -name testCases*

Sample output:

./test/testCases10.txt
./test/testCasesPassed.txt
./test/testCasesFailed.log

In the above case, we are only searching within the “./test” directory.

Find files by extension

To search and find files by a certain extension we use:

find . -name *.jpg

Sample output:

./test/results/failedTests.jpg
./test/project.jpg
./home/profile_pic.jpg
./tmp/cute-cats.jpg

Find files or directories with certain names

To find only files, we need to use the -f option:

find ./ -type f -name "results*"

Sample output:

./test/results_latest.log
./test/results_archive.pdf

To find only directories, we need to use the -d option:

find ./ -type d -name "results*"

Sample output:

./test/results

Find files in multiple directories

If you want to search and list all files with a given name in multiple directories you can either start the search at root folder, or if you know the directories, you can specify them.

Example:

find ./test ./logs -name failed*.* -type f

Sample output:

./test/failed_tests.txt
./logs/failed_tests.log

Find files containing a certain text

Sometimes you want to find a file and you don’t know its name, but you know it has a certain text inside it.

You can use:

find ./test -type f -exec grep -l -i "login_scenarios" {} ;

Here, the -i option is used to ignore case, so Login_Scenarios and login_scenarios will both be found.

Find files by size

We can even find files by different sizes. Size options are:

  • c bytes
  • k kilobytes
  • M Megabytes
  • G Gigabytes

For example to find files on an exact size we use:

find / -size 10M

And to find files which are greater than a certain size, we use:

find ./test -size +2M

The above will find all the files which are greater than 2MB in the ./test folder.

Find and delete specific files

To find and delete specific files we use:

find . -type f -name "temp*" -exec rm {} ;

Conclusion

In this article you learned about how to use the linux find command to search for files based on name, extension, size and type.