Fundamentals 15 min read

Master Linux Text Search: 30 Essential Grep Techniques You Need to Know

This comprehensive Linux tutorial explains why grep is indispensable, demonstrates basic and advanced string searches, multiple patterns, regex usage, recursive scans, whitespace handling, differences among grep variants, find vs grep, compressed‑file searches, IP and email extraction, case handling, exclusions, replacements, line numbers, context lines and result sorting.

ITPUB
ITPUB
ITPUB
Master Linux Text Search: 30 Essential Grep Techniques You Need to Know

Basic Usage

Grep searches for patterns in files or in the output of other commands. The simplest form pipes another command into grep and filters the lines that contain the given string. $ ls | grep Documents If the pattern is not found, grep produces no output, which can be used as a presence test.

Searching for Multiple Patterns

Use the -e option to specify several independent patterns. Each pattern that contains spaces must be quoted.

$ grep -e 'Class 1' -e 'Todd' Students.txt

Variants and Options

grep -E

or egrep: interpret the pattern as an extended regular expression (ERE). grep -F or fgrep: treat the pattern as a fixed string; no regex metacharacters are processed. pgrep: search the process table for running programs and return their PIDs (e.g., pgrep sshd). zgrep: search inside .gz compressed files without explicit decompression.

Recursive Search

The -r (or --recursive) flag makes grep descend into sub‑directories and search every regular file. $ grep -r "TODO" /path/to/project If no directory is supplied, grep searches the current working directory.

Finding Files vs. Searching Contents

find

locates files and directories based on name, type, size, etc. Use it when you need to filter filenames. grep searches inside file contents. They can be combined, for example:

$ find . -name "*.c" -print0 | xargs -0 grep -n "main"

Matching Whitespace

To match a literal space, enclose it in quotes. To match a tab character, press Ctrl+V then Tab inside the quotes.

$ grep " " file.txt          # space
$ grep "\t" file.txt         # tab

Regular‑Expression Basics

Grep’s power comes from regular expressions (regex). Common constructs:

Character class: grep "Class [123]" file.txt matches 1, 2, or 3.

Range: grep "Class [1-3]" file.txt is equivalent but easier to extend.

Start‑of‑line anchor: grep "^Class" file.txt.

Negated class: grep "Class [^1-2]" file.txt (any character except 1 or 2).

End‑of‑line anchor: grep "1$" file.txt.

Wildcard .: matches any single character, e.g., grep "A..a" file.txt.

Advanced Regex with -E

Extended regex enables repetition operators without backslashes. Example: find lines containing two consecutive p characters.

$ grep -E "p{2}" fruits.txt

Word‑Boundary Matching

To match a whole word, use -w or explicit word‑boundary markers \< and \> (escaped for the shell).

$ grep -w "apple" fruits.txt
$ grep "\<apple\>" fruits.txt

Case‑Insensitive Search

The -i flag makes the match case‑insensitive. For a single‑character case variation, a character class can be used.

$ grep -i "error" logfile.txt
$ grep "[Ss]tatus" file.txt

Inverting Matches

Use -v to exclude lines that contain a pattern.

$ grep -v "DEBUG" logfile.txt

Displaying Line Numbers and Context

-n

: prefix each matching line with its line number. -C N (or -A N / -B N): show N lines of context after, before, or both around each match.

$ grep -n "TODO" source.c
$ grep -C 2 "TODO" source.c   # 2 lines before and after
$ grep -A 3 "ERROR" log.txt    # 3 lines after

Counting Matches

-c

returns the number of matching lines instead of the lines themselves.

$ grep -c "FAIL" test.log

Extracting Only the Matching Part

-o

prints only the portion of the line that matches the pattern. This is useful for extracting email addresses or IPs.

$ grep -o '[[:alnum:]._%+-]\+@[[:alnum:].-]\+\.[[:alpha:].]{2,}' emails.txt
$ grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" logfile.txt

OR Conditions

Use the pipe character | inside an extended regex to match any of several alternatives.

$ grep -E "error|warning" syslog

Listing Files with Matches

-l

: list only the names of files that contain at least one match. -L: list files that contain no matches.

$ grep -rl "TODO" .   # recursive list of files containing TODO
$ grep -L "TODO" *.md   # files without TODO

Combining Grep with sed for Replacement

Find files containing a pattern and replace it globally with sed:

$ grep -rl "old" ./ | xargs sed -i 's/old/new/g'

Sorting Grep Output

Pipe grep results to sort for alphabetical ordering or other sort options.

$ grep "function" *.c | sort -u

Searching Compressed Files

zgrep

works like grep but reads .gz files directly.

$ zgrep "TODO" archive.log.gz
$ zcat archive.log.gz | grep "TODO"

Summary of Common Options

-i

: ignore case. -w: match whole words. -v: invert match. -r / -R: recursive search. -n: show line numbers. -C N, -A N, -B N: context lines. -c: count matches. -o: output only the matching portion. -l, -L: list matching / non‑matching files. -E: extended regular expressions. -F: fixed‑string search. -e: specify multiple patterns.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxregexGrepcommand-linetext search
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.