Contents

Mastering the grep Command in Linux

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

OptionDescription
-iCase-insensitive search
-vInverse match
-nShow line numbers
-rRecursive search
-lShow only filenames
-cCount matches
-wWhole-word match
-EExtended regular expressions
-AShow lines after match
-BShow 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
grep "Linux" sample.txt
Linux is awesome.

Example 2: Case-insensitive Search (-i)

grep -i "linux" sample.txt
Linuxisawesome.
linuxiscase-sensitive.

Example 3: Inverse Match (-v)

grep -v "error" sample.txt
Linuxisawesome.
WelcometoUbuntu.
linuxiscase-sensitive.
ERROR:Filenotfound.

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:Filenotfound.
5:Anotherlinewitherror.

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
Linuxisawesome.
WelcometoUbuntu.
ERROR:Filenotfound.
Anotherlinewitherror.

3. Quantifiers

grep -E 'e{2}' sample.txt  # Lines with double 'e'

4. Alternation

grep -E 'Linux|Ubuntu' sample.txt
Linuxisawesome.
WelcometoUbuntu.

Pro Tips

  1. Combine with other commands:

       ps aux | grep 'nginx'
    karna     202119  0.0  0.0   6408  3984 ?        SN   15:55   0:00 grep nginx
  2. Search multiple patterns:

       grep -e 'error' -e 'warning' log.txt
  3. Use context control:

       grep -A2 -B1 'critical' server.log