How to Search for Text in a File with grep
To find the lines of a file that contain a word, such as the errors in a log file, you don't need to open it: grep prints just the lines that match. This guide finds the errors in a four-line log, with real output from macOS's grep in zsh 5.9.
Syntax
grep [<options>] <pattern> <file>
| Part | What it means |
|---|---|
<pattern> | The text to look for. Upper and lower case must match |
<file> | The file to search |
[<options>] | Optional. -i ignores case, -n adds line numbers, -c prints only the number of matching lines |
The macOS manual page, man grep: "The grep utility searches any given input files, selecting lines that match one or more patterns."
Prerequisites
- A macOS or Linux terminal. This guide uses macOS's grep 2.6.0, "BSD grep, GNU compatible", in zsh 5.9, and checks it in bash 3.2 too.
Step 1: Find the Errors in a Log File
app.log has four lines:
INFO Server started
ERROR Disk is full
INFO Backup finished
ERROR Network is down
grep ERROR app.log
ERROR Disk is full
ERROR Network is down

grep printed the two lines that contain ERROR and left out the two INFO lines. bash printed the same.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Searching in the wrong case: grep error app.log | Nothing is printed: error doesn't match ERROR | Add -i: grep -i error app.log printed both lines |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
grep prints nothing | No line matches, often because of upper and lower case | Try -i, and check the spelling |
FAQ
How do I see which line each match is on?
Add -n. grep -n ERROR app.log printed 2:ERROR Disk is full and 4:ERROR Network is down.
How do I count the matches?
Add -c. grep -c ERROR app.log printed 2, the number of matching lines.
Conclusion
grep ERROR app.log printed the two error lines of the log. Add -i to ignore case, -n for line numbers and -c for a count.
Additional Resources
- GNU grep manual — every option of GNU grep.
