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: real-time search
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:
find /etc -name "sshd_config"/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:
find /home -iname "readme.md"Search by type
The -type option filters by kind of object:
| Value | Meaning |
|---|---|
f | Regular file |
d | Directory |
l | Symbolic link |
For example, find every directory named "config":
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.
| Suffix | Unit |
|---|---|
c | Bytes |
k | Kibibytes (KiB), 1,024 bytes |
M | Mebibytes (MiB), 1,048,576 bytes |
G | Gibibytes (GiB), 1,073,741,824 bytes |
b | Blocks 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.
# Files larger than 100 MiBfind /var/log -size +100M
# Empty files (0 bytes)find /tmp -size -1k
# Files smaller than 1000 bytes, empty files includedfind /tmp -size -1000cThe 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"):
mkdir ~/essai-size && cd ~/essai-sizetouch vide.txtprintf "bonjour" > note.txtfind . -type f -size -1k./vide.txtfind . -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:
# Files modified less than 7 whole days agofind /home -mtime -7
# Files modified at least 31 whole days agofind /var/log -mtime +30
# Files more than 7 days old, to the minute (7 x 24 x 60 = 10080)find /var/log -mmin +10080Search 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:
find /etc/ssh -type f -perm 600With 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:
find /tmp -type f -perm -002locate: 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
sudo apt install plocate# it really is plocate that ships, in the baseos repositorysudo dnf install plocatesudo updatedbsudo dnf install plocateThe 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:
sudo updatedbSearch for a file:
locate sshd_config/etc/ssh/sshd_config/usr/share/man/man5/sshd_config.5.gzTo ignore case:
locate -i readmegrep: 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.
grep "Port" /etc/ssh/sshd_config#Port 22Ignore case
-i makes the search case-insensitive, which avoids missing Error when you search for error.
grep -i "port" /etc/ssh/sshd_configSearch 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:
grep "error" *.logWhen grep searches several files, the file name appears in front of each result:
app.log:Apr 6 10:23:45 srv app[1234]: error: Could not load configSystem 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:
grep -r "AllowUsers" /etc/ssh/Show the line number
The -n option adds the line number in front of each result:
grep -n "PermitRootLogin" /etc/ssh/sshd_config33:#PermitRootLogin prohibit-passwordShow 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:
printf 'alpha\nbeta\ngamma\ndelta\nepsilon\nzeta\neta\ntheta\n' > letters.txtgrep -n -C 1 -e gamma -e theta letters.txt2-beta3:gamma4-delta--7-eta8:thetaThe 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.
Invert the search
The -v option prints the lines that do not contain the pattern, which is useful to filter out comments:
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.
| Need | Command |
|---|---|
| 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 date | find with -size, -type, -mtime |
| Search for text in a file | grep "pattern" file |
| Search for text in a whole folder | grep -r "pattern" /path/ |
| See the lines around a match | grep -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.
| Problem | Likely cause | Fix |
|---|---|---|
find: too many results | Search too broad | Narrow the starting path or add -name |
find: Permission denied | Protected directories | Add sudo, or discard the errors with 2>/dev/null (see the lesson on redirections and pipes) |
locate: recent file not found | Database not up to date | sudo updatedb |
locate: command not found | Package not installed | Install plocate |
grep: no result | Different case | Add -i to ignore case |
grep: Is a directory | You targeted a folder, not a file | Add -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
findwalks the disk in real time: slow, but always up to date and very flexible.locatequeries an index: fast, but possibly out of date.grepsearches for text inside files, not for file names. With-C 3, it also shows the three lines around each match.- Combine them:
findto locate,grepto 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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Filter and transform text on Linux
A new full quiz with random questions
Work again only on the questions you missed