$_ CLI In Depth
Learning progress 0%
lesson text-processing regex awk

Searching with grep

5 min read Module 6: Text Processing: grep, sed & awk Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:12

What grep does with its input

grep reads each named file, or standard input when no file is named, one line at a time. For every line it checks whether the pattern matches somewhere in the line. Matching lines are written to standard output, and by default nothing else is printed. The pattern is a regular expression in BRE by default, so the rules from the previous unit apply. With -E you get ERE, and with -F the pattern is a fixed string and no characters are special.

The input is a stream. grep does not need the whole file in memory, and it works equally well on a pipe from another command. That is why grep sits in the middle of so many pipelines.

Making a small test file

The examples below use a small log file that you create in your lab home directory. Creating the file first means every command has a known answer.

BASH1 lines
printf 'NFO start\nERROR disk full\nINFO retry\nerror timeout\nWARN slow\n'> app.log

This file has five lines, two of which contain an error in some form. The capital ERROR and the lowercase error are different strings to grep unless you ask it to ignore case.

The options you will use every day

The most useful options change what is printed. -i ignores case, -n prints line numbers, -c prints only the count of matching lines, and -v inverts the match so that non-matching lines are printed. -w requires the match to be a whole word, and -x requires it to be the whole line.

BASH3 lines
grep -in error app.log
grep -c INFO app.log
grep -v INFO app.log

The first command prints the two error lines with their numbers, because -i matches both spellings. The second prints 2, the number of INFO lines. The third prints the three lines that do not contain INFO. Notice that -c and -v change the output without changing the matching rule, which is why they combine well: grep -vc counts the non-matching lines.

Tip

Use -o to print only the matched part of each line. It is the fastest way to pull a value, such as an IP address or a version number, out of a longer line.

Context around a match

When a match matters only because of the lines around it, use -A for lines after, -B for lines before, and -C for both. grep prints a separator line between groups that are not adjacent. Context is especially useful with log files, where the cause of an error is usually a few lines above the message.

BASH1 lines
grep -B1 -A1 ERROR app.log

This prints the ERROR line with one line before and one line after it. Because the context lines are printed as they are, you can read the surrounding events without opening the whole file.

Searching many files

Give grep several file names to search them all, and each matching line is prefixed with its file name. With -r grep descends into directories. Use -l to list only the names of files that contain a match, and -L to list files that contain none. These options turn grep into a quick way to answer which files mention a symbol or setting.

BASH4 lines
mkdir -p notes
printf 'ODO fix\n'> notes/a.txt
printf 'one\n'> notes/b.txt
grep -rl TODO notes

The final command prints notes/a.txt only. The file notes/b.txt does not contain the word, so it is not listed.

Exit status: grep as a test

grep reports its result through the exit status. It returns 0 when at least one line matched, 1 when no line matched, and 2 when an error occurred, such as a file that does not exist. The quiet option -q suppresses output and only sets the status, which makes grep a natural condition in a script.

BASH2 lines
grep -q WARN app.log; echo "found=$?"
grep -q PANIC app.log; echo "found=$?"

The first line prints found=0 and the second prints found=1. The status 2 is the one to watch for in scripts, because it means the search itself failed. Treating a 1 and a 2 the same way hides real problems, such as a mistyped file name.

Whole words, whole lines, and case

Plain substring matching is often too loose. The word log matches inside blog and logger, and the search for INFO should not fire on INFORMATION. The option -w asks for whole words, meaning the match must be bordered by non-word characters or the ends of the line. The option -x is stricter, because the entire line must match, which is the right tool for checking that a line equals a given value.

BASH1 lines
printf 'og\nblog\nlogger\nlog file\n'| grep -w log

This prints log and log file. The lines blog and logger are rejected because the match is inside a longer word. Case is controlled separately with -i, and it applies to letters only, so a pattern with digits or punctuation is unaffected by it.

When you combine several patterns, use -e once for each one. A line is printed when it matches any of them, which is an OR across patterns. This is simpler than writing an alternation when the patterns are unrelated words.

BASH1 lines
grep -e ERROR -e WARN app.log

The output contains the ERROR and WARN lines, and the INFO lines are skipped. Use -f with a file of patterns when the list grows beyond a handful of words.

Fixed strings and a common trap

Patterns often contain characters that have special meaning, such as dots in an IP address or brackets in a log line. With -F grep treats the whole pattern as literal text, which is both safer and faster for plain words. Without it, the dot in 10.0.0.1 matches any character.

The trap is quoting. Always put the pattern in single quotes, because an unquoted pattern containing a star or a bracket may be expanded by the shell as a file name before grep sees it. The unit on quoting explains why that happens.

Matching a regex one position at a time

Visualizer

grep tries a match at each position, leftmost first, and the pattern decides how far the match runs. BRE and ERE differ mainly in which characters need a backslash.

1 / 5
p
o
r
t
␠
8
0
8
0
␠
o
p
e
n
pattern
[0-9]+
meaning
one or more digits

grep tries a match at position 0, then 1, and so on. It reports the leftmost position where a match succeeds, and at that position the longest one.

echo 'port 8080 open' | grep -o -E '[0-9]+'
Terminal lab · 3 steps · real Linux in your browser

Search a log

Count, show context, and find files with grep.

01
Count case-insensitive matches
The file app.log has lines containing ERROR and error. Count the lines that match error, ignoring case, and save the count: ``bash grep -ic error app.log > count.txt ``
Show hint for step 1
-i ignores case and -c prints the number of matching lines.
02
Show line numbers and context
Save the ERROR line with its line number and the line after it: ``bash grep -n -A1 ERROR app.log > context.txt ``
Show hint for step 2
-n adds line numbers and -A1 adds one line of trailing context.
03
List files that contain a word
The directory notes holds two files, and only one mentions TODO. List the names of the files that contain TODO, searching the directory recursively: ``bash grep -rl TODO notes > todo.txt ``
Show hint for step 3
-r searches a directory tree and -l prints only the file names.
Check yourself Question 1 of 4
Concept Check Exit status with no match recall

What exit status does grep return when it runs without error and no line matches the pattern?

Recap & Key Takeaways

grep prints matching lines, and the options -i, -n, -c, -v, -w, and -x change what is matched or printed.
Use -A, -B, and -C to show context, and -r with -l to search a directory tree and list matching file names.
grep exits 0 when something matched, 1 when nothing matched, and 2 on an error, so always distinguish 1 from 2 in scripts.
Use -F for fixed strings, and quote patterns in single quotes so the shell does not expand them first.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue