Skip to main content

How to Search for Text in a File with grep

· 2 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
grep [<options>] <pattern> <file>
PartWhat 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:

app.log
INFO Server started
ERROR Disk is full
INFO Backup finished
ERROR Network is down
Terminal
grep ERROR app.log
Output
ERROR Disk is full
ERROR Network is down

zsh running grep ERROR app.log, which prints the two ERROR lines of the log.

grep printed the two lines that contain ERROR and left out the two INFO lines. bash printed the same.

Common Mistakes​

MistakeWhat happensDo this instead
Searching in the wrong case: grep error app.logNothing is printed: error doesn't match ERRORAdd -i: grep -i error app.log printed both lines

Troubleshooting​

SymptomLikely causeFix
grep prints nothingNo line matches, often because of upper and lower caseTry -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​