Mastering the grep Command in Linux
Contents
Introduction
The grep
(Global Regular Expression Print) command is one of the most powerful text processing tools in Linux. It allows you to search through files or input streams using regular expressions, making it indispensable for programmers, system administrators, and anyone working with text data.
Why Learn grep?
- Quickly find information in files
- Filter log files efficiently
- Combine with other commands using pipes
- Search recursively through directories
- Powerful pattern matching with regular expressions
Basic Syntax
The basic syntax of grep is:
grep [options] pattern [file...]
Common Options Cheat Sheet
Option | Description |
---|---|
-i | Case-insensitive search |
-v | Inverse match |
-n | Show line numbers |
-r | Recursive search |
-l | Show only filenames |
-c | Count matches |
-w | Whole-word match |
-E | Extended regular expressions |
-A | Show lines after match |
-B | Show lines before match |
Practical Examples
Sample Files Setup
First, let’s create some sample files to work with.
echo "Linux is awesome.
Welcome to Ubuntu.
linux is case-sensitive.
ERROR: File not found.
Another line with error." > sample.txt
mkdir -p test_dir
echo "Grep examples in subdirectory
Linux command examples" > test_dir/subfile.txt
Example 1: Basic Search
grep "Linux" sample.txt
Linux is awesome.
Example 2: Case-insensitive Search (-i)
grep -i "linux" sample.txt
Linux | is | awesome. |
---|---|---|
linux | is | case-sensitive. |
Example 3: Inverse Match (-v)
grep -v "error" sample.txt
Linux | is | awesome. | |
---|---|---|---|
Welcome | to | Ubuntu. | |
linux | is | case-sensitive. | |
ERROR: | File | not | found. |
Example 4: Show Line Numbers (-n)
grep -n "Ubuntu" sample.txt
2:Welcome to Ubuntu.
Example 5: Count Matches (-c)
grep -c "linux" sample.txt
1
Example 6: Recursive Search (-r)
grep -r "examples" .
Example 7: Whole-word Match (-w)
grep -w "Linux" sample.txt
Linux is awesome.
Example 8: Combine Options (-in)
grep -in "error" sample.txt
4:ERROR: | File | not | found. |
---|---|---|---|
5:Another | line | with | error. |
Regular Expressions with grep
1. Anchoring
grep '^Linux' sample.txt # Lines starting with Linux
Linux is awesome.
2. Character Classes
grep '[A-Z]' sample.txt # Lines containing uppercase letters
Linux | is | awesome. | |
---|---|---|---|
Welcome | to | Ubuntu. | |
ERROR: | File | not | found. |
Another | line | with | error. |
3. Quantifiers
grep -E 'e{2}' sample.txt # Lines with double 'e'
4. Alternation
grep -E 'Linux|Ubuntu' sample.txt
Linux | is | awesome. |
---|---|---|
Welcome | to | Ubuntu. |
Pro Tips
Combine with other commands:
ps aux | grep 'nginx'
karna 202119 0.0 0.0 6408 3984 ? SN 15:55 0:00 grep nginx
Search multiple patterns:
grep -e 'error' -e 'warning' log.txt
Use context control:
grep -A2 -B1 'critical' server.log