Table of Contents
Why Searching Matters on the Command Line
On Linux, searching is usually faster and more flexible from the command line than from a graphical file search. Learning a few core tools lets you quickly:
- Find files by name or type.
- Search inside files for specific text, patterns, or configuration options.
- Combine searches with other commands using pipes.
This chapter focuses on search tools, not on general navigation or listing, which are covered elsewhere in this section.
Searching for Files by Name and Attributes with `find`
find searches the filesystem for files and directories that match given conditions (name, size, type, permissions, etc.).
Basic structure:
find [starting-point...] [conditions] [actions]Common starting points:
.– current directory (and below)/– entire filesystem (requiressudofor many parts)/home– all home directories
Matching by Name
Case-sensitive name match:
find . -name "file.txt"Case-insensitive name match:
find . -iname "file.txt"Using wildcards:
find . -name "*.log" # all .log files
find /var -name "syslog*" # files starting with "syslog"
Note: -name uses shell-like patterns (*, ?, []), not full regular expressions.
Limiting by Type
Filter to regular files, directories, etc.:
-type f– regular file-type d– directory-type l– symbolic link
Examples:
find . -type d -name ".git" # .git directories
find /etc -type f -name "*.conf" # config files under /etcCombining Conditions with `-and`, `-or`, `!`
Conditions are implicitly combined with -and. Use parentheses (escaped or quoted) to control grouping.
# All .log files larger than 1MB
find . -type f -name "*.log" -size +1M
# Files that are NOT .log
find . -type f ! -name "*.log"
# .conf OR .cfg files
find /etc \( -name "*.conf" -o -name "*.cfg" \) -type f
Note: In many shells you need to escape parentheses: \(, \).
Searching by Size and Time
Size examples:
# Files bigger than 100MB
find . -type f -size +100M
# Files smaller than 10KB
find . -type f -size -10kTime examples (based on days by default):
-mtime -7– modified less than 7 days ago-mtime +30– modified more than 30 days ago-mtime 0– modified within the last 24 hours
# Files changed in last 2 days
find . -type f -mtime -2Doing Something with Matches: `-print`, `-delete`, `-exec`
By default many find implementations already -print matches. You can explicitly specify actions.
Delete found files:
find . -type f -name "*.tmp" -delete
Be careful with -delete: test your conditions first without it.
Run a command for each match with -exec:
find . -type f -name "*.log" -exec ls -lh {} \;{}is replaced with the current file.\;ends the-execcommand.
Using + to run the command on batches of files:
find . -type f -name "*.log" -exec gzip {} +Searching Inside Files with `grep`
grep searches content of files for lines that match a given pattern.
Basic syntax:
grep [options] PATTERN [files...]
If no files are given, grep reads from standard input (useful with pipes).
Simple Text Search
grep "error" logfile.txt
This prints all lines in logfile.txt that contain the string error (case-sensitive).
Case-insensitive search:
grep -i "error" logfile.txtShow line numbers:
grep -n "error" logfile.txtSuppress file names (useful when searching a single file):
grep -h "error" logfile.txtSearching Multiple Files and Directories
Search in multiple specific files:
grep "main" file1.c file2.cSearch recursively in a directory tree:
grep -r "TODO" .-r(or-R) descends into subdirectories.
Exclude binary files (often implied when using grep on text trees):
grep -rI "TODO" .-Itreats binary files as if they do not contain matches.
Showing Context Around Matches
Sometimes you want to see lines around the match.
-n– show line numbers-C NUM– NUM lines of context before and after-A NUM– NUM lines after match-B NUM– NUM lines before match
Example:
grep -nC 2 "Listen" /etc/apache2/apache2.confThis shows 2 lines before and after each match, with numbers.
Matching Whole Words and Regular Expressions
Match whole words only:
grep -w "fail" logfile.txtMatch a regular expression (basic regex by default):
grep "^[0-9]\{3\}" file.txt # lines starting with 3 digits
Extended regular expressions (more powerful operators like +, ?, |) with -E:
grep -E "error|warning" logfile.txt
grep -E "^[0-9]+" file.txt
Note: Linux distributions often have egrep as a legacy shortcut for grep -E, but grep -E is preferred.
Counting and Listing File Names
Count matches instead of printing lines:
grep -c "error" logfile.txtShow only file names that contain matches:
grep -rl "TODO" .-lprints matching filenames only.- Combine with
-rto search tree-wise.
Combining `find` and `grep`
find locates files; grep searches their content. Together, they form a powerful combo.
Example: search for a string in all .conf files under /etc:
find /etc -type f -name "*.conf" -print0 | xargs -0 grep -n "Listen"Explanation of new pieces:
-print0prints file names separated by a NUL character instead of newlines (handles spaces, newlines).xargs -0reads NUL-separated input and passes file names safely togrep.
Simpler (but without advanced find filtering) is to just use recursive grep:
grep -rn "Listen" /etc --include="*.conf"Here:
--includerestricts which files are searched.-ris recursive.-nshows line numbers.
Quick Lookups for Commands and Binaries with `which`, `type`, `whereis`, `locate`
These are not general content search tools, but they help you find where commands and programs are located.
`which` and `type`
which shows the full path to an executable that will run when you type its name:
which bash
type is a shell builtin that tells you whether something is an alias, builtin, or external command, and where it lives:
type ls
type -a python`whereis`
whereis locates the binary, source, and man pages of a command:
whereis lsOutput might include paths to the executable and its manual pages.
`locate` and `updatedb`
locate searches a prebuilt database of file paths, making it very fast for name-based search.
locate filename
locate .bashrc
locate "*.png"Details:
- It does not search the live filesystem; it uses a database updated by
updatedb. - On many systems,
updatedbruns periodically (e.g., daily) via a scheduled job. - After creating many new files, you might update the database manually (with
sudo):
sudo updatedb
locate is ideal when:
- You know (part of) the filename.
- Exact freshness is not critical.
- You want speed over precision.
Filtering Output with `grep` and Pipes
Besides searching in files, grep is commonly used to search in command output.
Examples:
ps aux | grep ssh
dmesg | grep -i error
ls -l | grep "^d" # only lines for directories from ls -lThis pattern is extremely common:
- Run a command that produces many lines.
- Pipe (
|) togrepto keep only relevant lines.
Putting It All Together: Practical Examples
A few combined usage examples you’ll often see:
Find large .log files modified in the last week under /var/log:
find /var/log -type f -name "*.log" -mtime -7 -size +10M
Search for a configuration directive in all .conf files:
grep -rn "MaxClients" /etc --include="*.conf"
List all files under your home directory whose name contains ssh:
find ~ -iname "*ssh*"
Find all .py files and search them for import requests:
find . -type f -name "*.py" -print0 | xargs -0 grep -n "import requests"
Use locate to quickly find where a library or header is installed:
locate stdio.h
locate libssl.soThese patterns form the core of everyday file and content searching on Linux from the command line.