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

CommandPurposeMeaningBasic usageExample
findFind files and directoriesRecursively finds paths under a specified directoryfind path conditionsfind . -name "*.log"
grepSearch text contentMatches text in a file or input streamgrep [options] pattern filegrep "error" app.log
command -vInspect command resolutionPOSIX Shell query for how a command name resolvescommand -v namecommand -v python3
type -aInspect a Bash command sourceShows aliases, functions, builtins, and multiple file locationstype -a nametype -a python3
whichLegacy path-query toolImplementations vary and can omit aliases/functions/builtinswhich namewhich python3
whereisFind command-related filesFinds binary, source, and manual locationswhereis commandwhereis bash
locateFind files quicklyFinds paths using a system indexlocate keywordlocate 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 -7

Search file content:

grep "error" app.log
grep -r "deprecated_flag" ./src
grep -n "failed" app.log

Locate a command:

command -v -- python3
type -a -- python3
whereis bash

Notes 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 -r recursively searches a directory and is useful for finding a keyword in a project.
  • grep -n shows line numbers for easier location.
  • locate depends on an index, so it may not find a newly created file; find is more reliable in that situation.
  • find -mtime -7 uses rounded 24-hour periods, not the preceding seven calendar days.
  • Use grep -F for literal text and grep -E or 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.

References