ch02/l03

Read and search text under pressure

Use the right read/search tool for file size, context, and evidence.

grep -rn 25 min read, 35 min lab beginner

`cat` is fine for short files. `less` is safer for long files. `head`, `tail`, and `tail -f` answer bounded questions. `grep -rn` finds matching lines with file names and line numbers.

In the field

An app started failing after deploy. You need the first error line and surrounding context from copied logs.

Worked command

$ less app.log$ tail -n 50 app.log$ grep -rn "ERROR" ./logs$ grep -rn -C 3 "connection refused" ./logs
Anti-pattern

Do not dump huge or binary files into the terminal with `cat`.

Safer pattern

Pick bounded readers first, then search with file and line evidence.

Knowledge check

After a deploy, you need the first error and its surrounding context from a copied log to put file and line numbers in an incident note. Which command fits best?

  • A cat ./logs/app.log
  • B grep -r "ERROR" ./logs
  • C grep -rn -C 3 "ERROR" ./logs
  • D tail -f ./logs/app.log
Show the answer

Correct: C. grep -rn -C 3 "ERROR" ./logs

Why

grep -rn -C 3 reports each match with file name and line number (-n) and three lines of context (-C 3), exactly the file:line evidence an incident note needs. grep -r alone omits line numbers, cat dumps the whole file, and tail -f streams new lines instead of finding the existing error.

Practice checklist

  1. Create or copy sample logs into `/tmp/td-logs`.
  2. Find errors with line numbers.
  3. Extract context around one error.

Deliverable evidence

  • A grep command with constrained input.
  • A three-line incident summary with line numbers.
Teaching diagramch02 · mental model
Preview-first discipline: prove the target before you change it locate pwd preview ls / printf / stat act cp -i / mv / rm -i verify ls/stat shell expands the glob FIRST *.bak -> file1 file2 file3 rm only ever sees the final names read before you dump less / head -n / tail -f for bounded reads grep -rn gives file:line evidence never act from an unverified directory or an unpreviewed glob

shows: The repeated locate -> preview -> act -> verify loop behind every file change, plus the fact that the shell expands globs before the command ever runs and that bounded readers precede searching.

does not prove: The loop is a discipline, not a guarantee: a clean preview proves the target you saw, not that another process won't change the directory between preview and act, nor that flags like -a copied the right metadata.

Memorize this

Commit these to memory, then drill them until recall is automatic.

lesshead -ntail -fgrep -rn-C
Recall practice · Scenario -> next check

cue Search a log tree for an error and report file name, line number, and a few lines of context around each hit.

show recall target

grep -rn -C 3 "ERROR" ./logs