Searching Text with grep

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 21 of 205

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.

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

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:

SymbolMeaning
^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
\bA 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:

StatusMeaning
0At least one line matched
1No line matched
2An 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Searching Text with grep and get answers drawn from it.

Signed-in readers only.