How To Find Files In Linux Using The CLI
Have you ever been lost trying to find that one file buried deep down in the filesystem? Have you ever downloaded a file to your computer but you can't remember where you actually saved it? Have you ever wanted to find how many files containing your name in the filename is present in your system?
The find
command on linux is a powerful and flexible CLI tool that allows you to find the file(s) that you are looking for. The find
command is capable of finding files based on many different criteria such as filename, size, modified date, owner and so on. The output produced by the command can be a bit overwhelming if not used properly so, piping the output through other tools such as grep
and sed
can be very helpful.
Syntax
The basic syntax of using the find
command is:
find [options] [path...] [expression]
- The
options
attribute controls the treatment of the symbolic links, debugging options, and optimization method. - The
path...
attribute defines the starting directory or directories where find will search the files. - The
expression
attribute is made up of options, search patterns, and actions separated by operators.
Examples
Let's look at some of the examples.
1. Find file with a specific name
find / -name abc.txt 2>/dev/null
- This command will search for file named
abc.txt
as specified by the-name
flag. - The search begins from the root directory (
/
). - The use of
2>/dev/null
will redirect STDERR channel to/dev/null
so that the error messages wont be displayed in the terminal
2. Find files by extension
find ~ -name *.png
- This command will search the user's home directory to find all the files having
.png
extension.
3. Find directories
find ~ -name *oc* -type d
- The
-type
flag specifies the file type to search ford
means directory,b
means block,f
means regular file,l
means symbolic link.
4. Find in case-insensitive mode
find / -iname *something* -type f 2>/dev/null
- The
iname
flag tells thefind
command to search in case-insensitive mode.
5. Find files excluding specific paths
find ~ -name *.py -not -path '*/site-packages/*'
- This will exclude searching the paths that contains
site-packages
in them.
6. Find files greater than 500KB by specifying a maximum recursive depth to search in
find / -maxdepth 2 -size +500k 2>/dev/null
+500k
means greater than 500KB. If-500k
is used, it will search for size less than 500KB
7. Run a command for each file found
find ./ -name *.txt -exec wc -l {} \;
- each filename is in place of
{}
to execute the command specified by the-exec
flag.
8. Find files modified in the last 7 days
find / -daystart -mtime -7 2>/dev/null
9. Find empty files and delete them
find / -type f -empty -delete 2>/dev/null
There are still a lot of other options that can be used with the find
command. Read the man page to 'find' out more.