find locates files by name. grep looks inside them.
grep pattern file
grep ERROR server.log
ERROR database timeout
ERROR disk full
The file had six lines. Two of them contained ERROR, so those two came back — in full, exactly as they appear in the file.
That is grep’s entire model: go through the file line by line, keep the lines that contain the pattern, print them.
Note
The name comes from an old text-editor command, g/re/p. Nobody remembers that, and the word has long since become a verb — people say “grep the logs” the way they say “google it”.
Quick check
A file has 500 lines and 3 of them contain the word timeout. What does `grep timeout file.log` print?
The four flags worth knowing
| Flag | Effect |
|---|---|
-i | ignore case, so ERROR and error both match |
-n | show the line number of each match |
-c | print only how many lines matched |
-v | invert it: show the lines that do not match |
-v is the underrated one. When a log is 95 percent routine noise, filtering the noise out is often faster than describing the signal:
grep -v INFO server.log
Quick check
You want every line of a log EXCEPT the ones containing DEBUG. Which flag?
Silence means zero matches
grep TODO notes.txt
If nothing comes back, nothing matched. That is a real answer, not a failure — and it is different from an error, which would print something like No such file or directory.
Tip
When a search comes back empty and you expected results, try -i first. Roughly half the time the text is there and the capitalisation is not what you assumed.
Quick check
grep returns nothing at all. How do you tell 'no matches' from 'something went wrong'?
Try it
The log has six lines: four routine, two problems.
cat server.log— read the whole thing, so you can see what grep is filtering.grep ERROR server.log— the two lines that matter.grep -i error server.log— the same result, but now it would also catchErrororerror.
Then experiment: grep -v INFO server.log, grep -n ERROR server.log, grep -c INFO server.log. Six lines is small enough to check every answer by eye, which is the best way to build trust in a filter.