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.
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.txtVariants and Options
grep -Eor 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
findlocates 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 # tabRegular‑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.txtWord‑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.txtCase‑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.txtInverting Matches
Use -v to exclude lines that contain a pattern.
$ grep -v "DEBUG" logfile.txtDisplaying 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 afterCounting Matches
-creturns the number of matching lines instead of the lines themselves.
$ grep -c "FAIL" test.logExtracting Only the Matching Part
-oprints 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.txtOR Conditions
Use the pipe character | inside an extended regex to match any of several alternatives.
$ grep -E "error|warning" syslogListing 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 TODOCombining 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 -uSearching Compressed Files
zgrepworks 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
