05 Searching and Finding
Learning objectives
- Find files by name, type, and time.
- Search for keywords in file content.
- Locate the path of a command program.
Command overview
| Command | Purpose | Meaning | Basic usage | Example |
|---|---|---|---|---|
find | Find files and directories | Recursively finds paths under a specified directory | find path conditions | find . -name "*.log" |
grep | Search text content | Matches text in a file or input stream | grep [options] pattern file | grep "error" app.log |
command -v | Inspect command resolution | POSIX Shell query for how a command name resolves | command -v name | command -v python3 |
type -a | Inspect a Bash command source | Shows aliases, functions, builtins, and multiple file locations | type -a name | type -a python3 |
which | Legacy path-query tool | Implementations vary and can omit aliases/functions/builtins | which name | which python3 |
whereis | Find command-related files | Finds binary, source, and manual locations | whereis command | whereis bash |
locate | Find files quickly | Finds paths using a system index | locate keyword | locate nginx.conf |
Common scenarios
Find files by name:
find . -name "*.log"
find ./logs -type f -name "*.log"Find recently changed files:
find . -type f -mtime -7Search file content:
grep "error" app.log
grep -r "deprecated_flag" ./src
grep -n "failed" app.logLocate a command:
command -v -- python3
type -a -- python3
whereis bashNotes for beginners
find .starts at the current directory.find /scans the entire system. It can be slow, cross mount points, and collect irrelevant paths; practice only in a lab directory.grep -rrecursively searches a directory and is useful for finding a keyword in a project.grep -nshows line numbers for easier location.locatedepends on an index, so it may not find a newly created file;findis more reliable in that situation.find -mtime -7uses rounded 24-hour periods, not the preceding seven calendar days.- Use
grep -Ffor literal text andgrep -Eor default BRE for regular expressions. In a regular expression,.matches any single character.
Safe filenames and restricted scope
When passing find results to another command, prefer -exec ... {} +:
find ./logs -type f -name '*.log' -exec wc -l -- {} +It does not split legal file names on newlines. GNU/Linux also supports -print0 | xargs -0; see Text processing.
Exercise
In a lab directory, create three .log files and one log whose name contains a space. Complete four kinds of query: name, modification time, fixed string, and regular expression. For acceptance, record the starting path, hit count, and exit status; do not scan / or a real /var/log.