Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Find files on Linux

By updated

Improve this page

You know a file exists somewhere on the server, but you cannot find it again. On Linux, three commands answer this need: find walks the tree in real time, locate queries a prebuilt index to go faster, and grep searches for text inside files. This guide shows you the basic uses of each one.

What you will learn

  • Find a file by name with find
  • Filter by type, size or modification date
  • Search instantly with locate
  • Search for text in one or more files with grep, and show the lines around a match
  • Choose the right command for the situation

find walks the tree from a starting point and applies the criteria you give it. It filters on name, type, size, date and permissions, but it is slower than locate on large filesystems. The more precise the starting point, the fewer directories find has to walk: find / -name "sshd_config" searches the whole disk and can take a long time, whereas find /etc -name "sshd_config" answers almost at once.

Search by name

You give find a starting directory, then the -name criterion with the name of the file you are looking for:

Terminal window
find /etc -name "sshd_config"
Output
/etc/ssh/sshd_config
  • /etc: the directory where the search starts
  • -name: compares the file name with a pattern; without a wildcard (* stands for any run of characters, ? for a single character), the name must be identical to the pattern

-name is case-sensitive: find /home -name "readme.md" does not find a file named README.md. To ignore case, use -iname:

Terminal window
find /home -iname "readme.md"

Search by type

The -type option filters by kind of object:

ValueMeaning
fRegular file
dDirectory
lSymbolic link

For example, find every directory named "config":

Terminal window
find /etc -type d -name "config"

Search by size

The -size option filters by size. You write a number followed by a letter that gives the unit. A + in front of the number means "more than", a - "less than", nothing "equal to", after the rounding explained below.

SuffixUnit
cBytes
kKibibytes (KiB), 1,024 bytes
MMebibytes (MiB), 1,048,576 bytes
GGibibytes (GiB), 1,073,741,824 bytes
bBlocks of 512 bytes

The letters k, M and G stand for binary units: a kibibyte is 1,024 bytes, whereas a kilobyte is 1,000. M is therefore a little more than a megabyte (1,000,000 bytes). With no letter, find counts in blocks of 512 bytes (b), not in bytes: always write the letter.

With any unit other than c (b, k, M, G), find rounds the file size up to the next unit before comparing: -size -1k therefore only keeps files of 0 bytes, not every file "smaller than 1 KiB". With c, there is no rounding.

Terminal window
# Files larger than 100 MiB
find /var/log -size +100M
# Empty files (0 bytes)
find /tmp -size -1k
# Files smaller than 1000 bytes, empty files included
find /tmp -size -1000c

The first command prints the files of /var/log larger than 100 MiB, the second the empty files of /tmp, the third those smaller than 1000 bytes. To see the rounding at work, create an empty file and a 7-byte file in a practice folder (the names are French: essai means "test", vide "empty", bonjour "hello"):

Terminal window
mkdir ~/essai-size && cd ~/essai-size
touch vide.txt
printf "bonjour" > note.txt
find . -type f -size -1k
./vide.txt
Terminal window
find . -type f -size -1000c
./note.txt
./vide.txt

-size -1k only keeps vide.txt: rounded up to the next KiB, note.txt (7 bytes) counts as 1 KiB, which is not "less than 1 KiB". -size -1000c counts in bytes and keeps both files. The order of the lines is the order on the disk: find does not sort. Then delete the practice folder: cd ~ && rm -r ~/essai-size.

Search by modification date

The -mtime option counts in whole 24-hour days and truncates the age of the file: -7 means "age below 7", so modified less than 7 whole days ago, and +30 "age above 30", so modified at least 31 whole days ago. -mtime +7 therefore does not mean "more than 7 days": a file 7 and a half days old has age 7 and is not kept. It is the criterion for cleaning old logs:

Terminal window
# Files modified less than 7 whole days ago
find /home -mtime -7
# Files modified at least 31 whole days ago
find /var/log -mtime +30
# Files more than 7 days old, to the minute (7 x 24 x 60 = 10080)
find /var/log -mmin +10080

Search by permissions

The -perm option filters on permissions, that is the read, write and execute rights. With an octal value alone, find keeps only the files whose permissions are exactly those. This command lists the files of /etc/ssh set to 600, readable and writable by their owner alone:

Terminal window
find /etc/ssh -type f -perm 600

With a dash in front of the value, find keeps the files that have at least those rights. -perm -002 therefore finds the files that anyone can modify:

Terminal window
find /tmp -type f -perm -002

locate: instant search through an index

locate is much faster than find because it queries a prebuilt database instead of walking the disk. The trade-off is that this database only keeps the names of files: locate cannot filter on size or on modification date. For "files larger than 100 MiB modified this week", you need find.

Install and use it

Terminal window
sudo apt install plocate

The database is also rebuilt periodically by a scheduled task shipped with the package, at a pace that depends on the distribution. To update it right away:

Terminal window
sudo updatedb

Search for a file:

Terminal window
locate sshd_config
Output
/etc/ssh/sshd_config
/usr/share/man/man5/sshd_config.5.gz

To ignore case:

Terminal window
locate -i readme

grep: search for text inside files

grep (Global Regular Expression Print) searches for a text string inside files. Where find and locate search by file name, grep searches by content.

Search for a word in a file

grep prints the whole lines that contain the pattern, not just the matching word.

Terminal window
grep "Port" /etc/ssh/sshd_config
Output
#Port 22

Ignore case

-i makes the search case-insensitive, which avoids missing Error when you search for error.

Terminal window
grep -i "port" /etc/ssh/sshd_config

Search in several files

The pattern *.log stands for every file of the current directory whose name ends in .log. Here, the directory contains the application log file app.log:

Terminal window
grep "error" *.log

When grep searches several files, the file name appears in front of each result:

Output
app.log:Apr 6 10:23:45 srv app[1234]: error: Could not load config

System logs live elsewhere, at a location that varies by distribution: give grep the path of the one you are looking for.

Search a folder recursively

Without an option, grep expects files: on a folder, it answers Is a directory. The -r (recursive) option makes it walk every file and subdirectory:

Terminal window
grep -r "AllowUsers" /etc/ssh/

Show the line number

The -n option adds the line number in front of each result:

Terminal window
grep -n "PermitRootLogin" /etc/ssh/sshd_config
Output
33:#PermitRootLogin prohibit-password

Show the context around a match

A matching line is often easier to understand with its neighbouring lines: the section of a configuration file, or what comes before an error in a log. The -C 2 (context) option prints two lines before and two lines after each match. -B 2 (before) prints only the lines before, -A 2 (after) only the lines after. The short form -2 is equivalent to -C 2, but it reads less well in a script. Combined with -n, the context option locates each line in the file.

To try it, create a small eight-line file, then search for two words at once: -e introduces a pattern, and you can repeat it to give several. With -C 1, each match is surrounded by one line before and one line after:

Terminal window
printf 'alpha\nbeta\ngamma\ndelta\nepsilon\nzeta\neta\ntheta\n' > letters.txt
grep -n -C 1 -e gamma -e theta letters.txt
Output
2-beta
3:gamma
4-delta
--
7-eta
8:theta

The separator that follows the number tells the two kinds of lines apart: : for a line that contains the pattern, - for a context line. When two matches are too far apart for their contexts to touch, grep inserts a -- line between the two groups. On a real file, grep -n -C 3 "PermitRootLogin" /etc/ssh/sshd_config thus shows the directive in the middle of its paragraph of comments.

The -v option prints the lines that do not contain the pattern, which is useful to filter out comments:

Terminal window
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"

This command removes the lines that start with # (comments) and the empty lines.

To go further, the reference guides cover find (combinations, -exec, safe deletion) and grep (regular expressions).

Which search command should you choose?

The question to ask first is what you know: the name of the file, its characteristics, or a word it contains. The table maps each case to its command.

NeedCommand
Find a file by name (reliable result)find /path -name "name"
Find a file by name (fast result)locate name
Filter by size, type or datefind with -size, -type, -mtime
Search for text in a filegrep "pattern" file
Search for text in a whole foldergrep -r "pattern" /path/
See the lines around a matchgrep -n -C 3 "pattern" file

Troubleshooting

Most search failures come from a scope that is too wide or too narrow, or from case. The table sorts them by the symptom you see.

ProblemLikely causeFix
find: too many resultsSearch too broadNarrow the starting path or add -name
find: Permission deniedProtected directoriesAdd sudo, or discard the errors with 2>/dev/null (see the lesson on redirections and pipes)
locate: recent file not foundDatabase not up to datesudo updatedb
locate: command not foundPackage not installedInstall plocate
grep: no resultDifferent caseAdd -i to ignore case
grep: Is a directoryYou targeted a folder, not a fileAdd -r for recursion

Put it into practice

Practise locating files with find, the search skill expected at the fundamentals level. The exercise also touches on permissions: if they are not familiar to you yet, the optional box above and the permissions lesson explain them.

Key points

  • find walks the disk in real time: slow, but always up to date and very flexible.
  • locate queries an index: fast, but possibly out of date.
  • grep searches for text inside files, not for file names. With -C 3, it also shows the three lines around each match.
  • Combine them: find to locate, grep to inspect the contents.

Knowledge check

Check that the essentials of this guide stuck. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer