grep ‐ #files - five4nets/Linux-Knowledgebase GitHub Wiki

Tutorial: Using the Linux grep Command

The grep command in Linux is a powerful tool for searching text patterns within files or input streams. It stands for Global Regular Expression Print and allows users to filter and display lines matching a specified pattern. This tutorial covers grep basics, common options, and practical examples, with references for further reading.

Table of Contents

Basic Syntax

grep [options] pattern [file...]
  • pattern: The text or regular expression to search for.
  • file: One or more files to search (optional; if omitted, grep reads from standard input).
  • options: Flags to modify grep behavior (e.g., case sensitivity, output format).

Common Options

Option Description
-i Ignore case sensitivity (match uppercase/lowercase).
-r Recursively search directories and their files.
-n Display line numbers with matching lines.
-v Invert match (show lines that don't match the pattern).
-w Match whole words only.
-c Count the number of matching lines.
-E Use extended regular expressions (ERE).
-l List only filenames containing matches.
--color Highlight matches in color (often enabled by default).

Examples

Basic Pattern Search

Search for the word "error" in a log file:

grep "error" logfile.txt

Output (example):

2025-06-25 10:00:01 error: connection failed
2025-06-25 10:01:15 error: timeout occurred

Case-Insensitive Search

Search for "error" ignoring case (e.g., matches "Error", "ERROR"):

grep -i "error" logfile.txt

Output (example):

2025-06-25 10:00:01 ERROR: connection failed
2025-06-25 10:01:15 error: timeout occurred

Recursive Search

Search for "function" in all .py files in a directory and its subdirectories:

grep -r "function" /path/to/project/*.py

Output (example):

/path/to/project/script1.py:10:def function_name():
/path/to/project/subdir/script2.py:25:function example()

Line Number Output

Show line numbers for matches of "TODO" in a file:

grep -n "TODO" code.py

Output (example):

15:# TODO: optimize this loop
42:# TODO: add error handling

Inverted Search

Display lines that don't contain "debug":

grep -v "debug" logfile.txt

Output (example):

2025-06-25 10:00:01 error: connection failed
2025-06-25 10:02:00 info: system started

Regular Expression Search

Use extended regex to match email addresses in a file:

grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt

Output (example):

[email protected]
[email protected]

Counting Matches

Count how many lines contain "warning":

grep -c "warning" logfile.txt

Output (example):

5

Matching Whole Words

Match the word "test" but not "testing" or "contest":

grep -w "test" document.txt

Output (example):

This is a test case.
Run the test now.

References