Searching Text with grep
The grep command reads text and prints the lines that match a pattern. The name comes from an old editor command, g/re/p, which meant "globally search for a regular expression and print". Where find locates files by their properties, grep looks inside the files at their content. It is one of the tools you will use most often in Bash: to read a log file for errors, to find where a function is defined, or to filter the output of another command.
Understanding the Concept
grep reads its input one line at a time. For each line, it tests whether the pattern appears anywhere in the line. If the test succeeds, grep prints the whole line; if not, it skips it. Because it works line by line, a match tells you which lines contain the text, not just that the text exists somewhere in the file.
The basic form is:
grep [OPTIONS] PATTERN [FILE...]
The pattern comes first and the files come after it. If you give no file, grep reads standard input, which is what makes it useful at the end of a pipeline.
The examples in this lesson use a small project:
.
├── logs/
│ └── app.log
└── src/
├── app.py
└── util.py
The file logs/app.log contains these eight lines:
2026-11-20 09:00:01 INFO Server started on port 8080
2026-11-20 09:00:05 INFO User alice logged in
2026-11-20 09:01:12 WARN Disk usage at 85%
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:02:50 INFO Retrying connection
2026-11-20 09:03:01 ERROR Timeout while reading from cache
2026-11-20 09:04:30 INFO User bob logged in
2026-11-20 09:05:00 info Health check ok
The file src/app.py contains two comments that start with TODO, and src/util.py defines one function named add.
Basic Search
To print every line that contains ERROR, give the word and the file name:
grep ERROR logs/app.log
Output:
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:03:01 ERROR Timeout while reading from cache
Matching is case sensitive and also works inside longer words: a pattern of ERROR would match ERRORS or NOERROR too. The pattern may contain spaces, but then it must be quoted so that the shell passes it as one argument:
grep "port 8080" logs/app.log
Output:
2026-11-20 09:00:01 INFO Server started on port 8080
Without the quotes, the shell would hand grep three words, and grep would treat 8080 and logs/app.log as file names.
Common Options
Showing Line Numbers
The -n option adds the line number to every match, so you can jump straight to that line in an editor:
grep -n ERROR logs/app.log
Output:
4:2026-11-20 09:02:44 ERROR Database connection failed
6:2026-11-20 09:03:01 ERROR Timeout while reading from cache
Ignoring Case
The log has a lowercase info on its last line. Plain grep INFO skips it, but -i ignores the difference between uppercase and lowercase:
grep -i info logs/app.log
Output:
2026-11-20 09:00:01 INFO Server started on port 8080
2026-11-20 09:00:05 INFO User alice logged in
2026-11-20 09:02:50 INFO Retrying connection
2026-11-20 09:04:30 INFO User bob logged in
2026-11-20 09:05:00 info Health check ok
Counting Matches
The -c option prints how many lines matched instead of the lines themselves. It counts lines, not occurrences, so a line with the pattern twice is counted once:
grep -c INFO logs/app.log
Output:
4
Inverting the Match
The -v option selects the lines that do not match. Here it shows everything that is not an INFO line:
grep -v INFO logs/app.log
Output:
2026-11-20 09:01:12 WARN Disk usage at 85%
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:03:01 ERROR Timeout while reading from cache
2026-11-20 09:05:00 info Health check ok
Matching Whole Words
The -w option requires the match to be a complete word, which means the characters before and after it must not be letters, digits or underscores. This command counts the lines in which ERROR stands alone as a word:
grep -w ERROR logs/app.log | wc -l
Output:
2
Printing Only the Matching Part
The -o option prints just the part of the line that matched, one match per line. Together with a pattern that describes a range of text, it extracts values from lines:
grep -o "User [a-z]*" logs/app.log
Output:
User alice
User bob
The pattern [a-z]* means "zero or more lowercase letters", so the match ends where the name ends.
Searching Many Files
Recursive Search
To search every file below a directory, add -r. When more than one file is involved, grep puts the file name before each match:
grep -rn TODO src
Output:
src/app.py:5: # TODO: validate the config
src/app.py:9: print("Starting") # TODO: add logging
The format is file:line:text. The order in which grep -r visits files is decided by the file system, so with more files your output may come in a different order. Pipe it through sort when you need a stable order.
Listing Only File Names
The -l option prints just the names of files that contain a match, and -L prints the names of files that do not:
grep -rl TODO .
grep -rL TODO src
Output:
./src/app.py
src/util.py
Restricting the Search to Certain Files
The --include option limits a recursive search to file names that match a pattern. This command finds every function definition in the Python files:
grep -rn "def " --include="*.py" .
Output (the order of the files may differ on your system):
./src/util.py:1:def add(a, b):
./src/app.py:4:def load_config(path):
./src/app.py:8:def main():
Quote the *.py pattern so that grep applies it while walking the tree instead of the shell expanding it first.
Counting per File
When you give several files, or use -r, the -c option reports one count for each file, including files with no match:
grep -r -c TODO src
Output (file order may differ):
src/util.py:0
src/app.py:2
Showing Context Around a Match
An error line is more useful when you can see what happened around it. Three options print neighboring lines: -A N for N lines after the match, -B N for N lines before it, and -C N for N lines on both sides.
grep -A1 ERROR logs/app.log
Output:
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:02:50 INFO Retrying connection
2026-11-20 09:03:01 ERROR Timeout while reading from cache
2026-11-20 09:04:30 INFO User bob logged in
The first ERROR is followed by the retry line, and the second by a login. When the context ranges of two matches touch or overlap, grep prints them as one continuous block. When there is a gap between blocks, grep separates them with a line containing --.
grep -B1 "Retrying" logs/app.log
grep -C1 WARN logs/app.log
Output of the second command:
2026-11-20 09:00:05 INFO User alice logged in
2026-11-20 09:01:12 WARN Disk usage at 85%
2026-11-20 09:02:44 ERROR Database connection failed
Using Regular Expressions
A pattern is not just literal text. By default grep reads it as a basic regular expression, in which some characters have special meaning. The most useful ones are:
| Symbol | Meaning |
|---|---|
^ | The start of a line |
$ | The end of a line |
. | Any single character |
* | Zero or more of the previous item |
[abc] | Any one of the listed characters |
[0-2] | Any one character in the range |
\b | A word boundary |
Anchoring a pattern with ^ selects lines by how they begin. This command prints the entries logged between 09:00 and 09:02:
grep "^2026-11-20 09:0[0-2]" logs/app.log
Output:
2026-11-20 09:00:01 INFO Server started on port 8080
2026-11-20 09:00:05 INFO User alice logged in
2026-11-20 09:01:12 WARN Disk usage at 85%
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:02:50 INFO Retrying connection
Extended Regular Expressions with -E
The -E option switches to extended regular expressions, in which | means "or", + means "one or more", and parentheses group parts of the pattern without needing backslashes.
grep -E "ERROR|WARN" logs/app.log
Output:
2026-11-20 09:01:12 WARN Disk usage at 85%
2026-11-20 09:02:44 ERROR Database connection failed
2026-11-20 09:03:01 ERROR Timeout while reading from cache
A second example finds lines that begin with import or from, which lists the imports of a Python file:
grep -E "^(import|from) " src/app.py
Output:
import os
import sys
The same alternation can be written with several -e options, one for each pattern: grep -e ERROR -e WARN logs/app.log prints the same three lines.
Searching for Text That Looks Like a Pattern
A line such as Disk usage at 85% has no special characters, but text such as a.b or 1+1 does. The -F option treats the pattern as plain text with no special characters at all:
grep -F "85%" logs/app.log
Output:
2026-11-20 09:01:12 WARN Disk usage at 85%
Use -F whenever the text you are looking for comes from a user or a variable and might contain symbols such as ., * or [.
Exit Status and Scripts
Every grep run ends with an exit status that scripts can test:
| Status | Meaning |
|---|---|
0 | At least one line matched |
1 | No line matched |
2 | An error occurred, such as a missing file |
grep nothing_here logs/app.log
echo "status=$?"
grep ERROR missing.log
echo "status=$?"
Output:
status=1
grep: missing.log: No such file or directory
status=2
A status of 1 is not an error. It only reports that the pattern was not found. With the -q (quiet) option, grep prints nothing and only sets the status, which suits an if test:
if grep -q ERROR logs/app.log; then
echo "found errors"
fi
Output:
found errors
The -s option hides messages about missing or unreadable files, but it does not change the status, so a missing file still returns 2.
Filtering Output with a Pipe
When grep has no file argument, it reads standard input, so it can filter the output of any command:
printf 'one\ntwo\nthree\n' | grep t
Output:
two
three
The printf command writes three lines, and grep keeps the two that contain the letter t. You will use this pattern with commands that produce long listings, such as process lists and directory listings, to pick out only the lines you care about.
Practical Applications
Finding every place a setting appears across a project, with line numbers and no output from binary files such as images:
grep -rnIi "timeout" .
Output:
./logs/app.log:6:2026-11-20 09:03:01 ERROR Timeout while reading from cache
The -I option skips binary files, and -i makes the search ignore case, which is why the capital T in Timeout matched.
Counting the lines of each log level, one command at a time:
grep -c ERROR logs/app.log
grep -c WARN logs/app.log
Showing the first error only, which is handy when a log has thousands of lines. The -m 1 option stops after one match:
grep -m 1 ERROR logs/app.log
Output:
2026-11-20 09:02:44 ERROR Database connection failed
Checking a configuration file for a required line before a script goes on:
grep -qx "enabled=true" settings.conf || echo "feature is disabled"
The -x option requires the whole line to equal the pattern, so enabled=true # old would not count as a match.