Skip to content

grep Command — Searching Text in Linux

The grep command is one of the most powerful and frequently used Linux utilities. It searches text for specific patterns, making it indispensable for system administration, DevOps, Cloud Engineering, cybersecurity, and troubleshooting. If you master grep, you'll be able to analyze logs, configuration files, and command outputs with incredible speed.


Learning Path

Linux Mastery → Module 3: Text Processing → Lesson 2

Difficulty: Beginner → Intermediate

Reading Time: 35 Minutes

Course Progress

Course: Linux Mastery

Module: Text Processing

Lesson: 2 of 18


What You'll Learn

After completing this lesson, you'll be able to:

  • Understand the grep command
  • Search text inside files
  • Search multiple files
  • Perform case-insensitive searches
  • Count matching lines
  • Display line numbers
  • Search recursively
  • Use Basic Regular Expressions
  • Analyze production log files

Prerequisites

Before starting this lesson, complete:

  • Module 1 – Linux Fundamentals
  • Module 2 – Linux Command Line Essentials
  • Module 3 Lesson 1 (cat)

Why Learn grep?

Imagine you're managing a production server with a log file containing 2 million lines.

You're looking for:

  • ERROR
  • WARNING
  • nginx
  • ssh
  • Kubernetes
  • Database failures

Instead of manually reading the file, use:

grep ERROR application.log

Instant results.

This is why grep is one of the most used Linux commands.


What is grep?

grep stands for:

Global Regular Expression Print

It searches files or command output for text that matches a pattern.

Syntax:

grep [OPTIONS] PATTERN FILE

Sample File

Create a sample file.

cat > employees.txt

Contents:

Alice Engineering

Bob HR

Charlie Engineering

David Finance

Eve Engineering

Press:

Ctrl + D

Basic Search

Search for:

grep Engineering employees.txt

Output:

Alice Engineering

Charlie Engineering

Eve Engineering

Case-Insensitive Search

Normally:

grep linux file.txt

does not match:

Linux

Use:

grep -i linux file.txt

Matches:

Linux

LINUX

linux

Display Line Numbers

grep -n Engineering employees.txt

Output:

1: Alice Engineering

3: Charlie Engineering

5: Eve Engineering

Count Matches

grep -c Engineering employees.txt

Output:

3

Invert Match

Display everything except Engineering.

grep -v Engineering employees.txt

Output:

Bob HR

David Finance

Search Multiple Files

grep ERROR app.log server.log

Output:

app.log:ERROR Database Down

server.log:ERROR Connection Failed

Recursive Search

Search every file in a directory.

grep -r nginx /etc

Useful for finding configuration values.


Search Whole Words

Suppose:

cat

catalog

category

Search:

grep cat file.txt

Matches all three.

Search whole word only:

grep -w cat file.txt

Output:

cat

Match Beginning of Line

grep "^Alice" employees.txt

Output:

Alice Engineering

Match End of Line

grep "Engineering$" employees.txt

Matches only lines ending with:

Engineering

Search Multiple Patterns

grep -E "ERROR|WARNING" app.log

Matches:

ERROR

WARNING

Ignore Binary Files

grep -I ERROR *

Useful when searching directories containing binary files.


Search with Color

grep --color=auto ERROR app.log

Matches are highlighted.


Search Command Output

Find SSH process.

ps -ef | grep ssh

Search Docker containers.

docker ps | grep nginx

Search Kubernetes Pods.

kubectl get pods | grep Running

Search Configuration Files

NGINX

grep server_name /etc/nginx/nginx.conf

SSH

grep PermitRootLogin /etc/ssh/sshd_config

Hosts

grep localhost /etc/hosts

Basic Regular Expressions

Match lines starting with "A".

grep "^A" employees.txt

Match lines ending with "HR".

grep "HR$" employees.txt

Match any line containing numbers.

grep "[0-9]" file.txt

Match lowercase letters.

grep "[a-z]" file.txt

Common grep Options

Option Description
-i Ignore case
-n Show line numbers
-v Invert match
-c Count matches
-r Recursive search
-w Whole words only
-l Display filenames only
-E Extended regular expressions

Real Production Examples

Find failed logins.

grep "Failed password" /var/log/auth.log

Find Kubernetes errors.

kubectl logs pod-name | grep ERROR

Search Docker logs.

docker logs container | grep Exception

Search NGINX errors.

grep 500 access.log

Search system logs.

journalctl | grep CRITICAL

Production Perspective

Engineers use grep daily for:

  • Searching logs
  • Finding configuration values
  • Debugging applications
  • Monitoring services
  • Incident response
  • Security investigations

Learning grep is one of the fastest ways to improve Linux troubleshooting skills.


Hands-on Lab

Task 1

Create:

cat > servers.txt

Contents:

server01 Running

server02 Stopped

server03 Running

server04 Failed

server05 Running

Task 2

Search:

grep Running servers.txt

Task 3

Ignore case.

grep -i running servers.txt

Task 4

Display line numbers.

grep -n Running servers.txt

Task 5

Count running servers.

grep -c Running servers.txt

Task 6

Display non-running servers.

grep -v Running servers.txt

Task 7

Search beginning of line.

grep "^server01" servers.txt

Task 8

Search end of line.

grep "Running$" servers.txt

Command Deep Dive

Command Purpose Production Example
grep text file Search text Find configs
grep -i Ignore case Search logs
grep -n Line numbers Debug configs
grep -c Count matches Count errors
grep -v Exclude matches Filter logs
grep -r Recursive search Search /etc
grep -w Whole words Match exact values
grep -E Multiple patterns ERROR or WARNING

Production Troubleshooting Scenario

Scenario

Users report that an application is failing.

Tasks:

  1. Find all ERROR messages.
  2. Count the number of ERROR entries.
  3. Display only WARNING and ERROR messages.
  4. Search configuration files for database settings.
  5. Find failed SSH login attempts.

Solutions:

grep ERROR app.log

grep -c ERROR app.log

grep -E "ERROR|WARNING" app.log

grep -r database /etc/myapp

grep "Failed password" /var/log/auth.log

Mini Challenge

Create:

application.log

Contents:

INFO Server Started

INFO User Login

WARNING High Memory Usage

ERROR Database Connection Failed

INFO Health Check Passed

ERROR API Timeout

WARNING Disk Space Low

Perform the following:

  • Display all ERROR messages.
  • Display all WARNING messages.
  • Count ERROR messages.
  • Show line numbers for WARNING messages.
  • Display everything except INFO.
  • Search for both ERROR and WARNING together.

Best Practices

  • Use grep -i when case doesn't matter.
  • Use grep -n while editing configuration files.
  • Use grep -c to count matching lines.
  • Combine grep with pipes for powerful filtering.
  • Learn regular expressions to unlock the full power of grep.

Common Mistakes

❌ Searching recursively from the filesystem root.

✅ Use:

grep -r error /

This can be very slow.

Instead:

grep -r error /var/log

❌ Forgetting quotes around patterns containing special characters.

✅ Use:

grep "^ERROR" app.log

❌ Confusing grep with find.

✅ - find searches files - grep searches inside files


Interview Questions

Beginner

  1. What does grep stand for?
  2. How do you search for text in a file?
  3. What does grep -i do?
  4. What does grep -v do?

Intermediate

  1. Difference between grep and find?
  2. Explain grep -r.
  3. What is grep -E?
  4. How do you count matching lines?

Architect Level

  1. How would you analyze a 10 GB application log?
  2. Why is grep one of the most important Linux troubleshooting tools?
  3. How can grep improve incident response during production outages?

Summary

In this lesson, you learned:

  • Searching text with grep
  • Case-insensitive searches
  • Counting matches
  • Recursive searches
  • Whole-word matching
  • Basic regular expressions
  • Production log analysis

grep is one of the most valuable Linux commands. Combined with pipes, regular expressions, and other text-processing tools, it becomes an essential part of every Linux engineer's toolkit.


Key Takeaways

  • grep searches text inside files and command output.
  • grep -i ignores case differences.
  • grep -n displays line numbers.
  • grep -c counts matching lines.
  • grep -v excludes matching lines.
  • grep -r searches directories recursively.
  • Mastering grep significantly improves troubleshooting and log analysis.

What's Next?

cut Command — Extracting Columns from Text

In the next lesson, you'll learn:

  • Extracting fields from structured text
  • Working with delimiters
  • Selecting multiple columns
  • Processing CSV and log files
  • Real-world text extraction techniques