Lab 12: grep — Searching Text

Objective

Use grep to search files and command output: case-insensitive search, line numbers, inverted match, count, regex patterns, and recursive search. grep is the #1 tool for log analysis and config auditing.

Time: 25 minutes | Level: Foundations | Docker: docker run -it --rm ubuntu:22.04 bash


Step 1: Basic grep

printf 'apple\nbanana\napricot\nblueberry\ncherry\n' > /tmp/fruits.txt
cat /tmp/fruits.txt

📸 Verified Output:

apple
banana
apricot
blueberry
cherry
grep 'a' /tmp/fruits.txt

📸 Verified Output:

apple
banana
apricot

💡 grep prints every line that contains the pattern. By default it's case-sensitive — grep 'Apple' would find nothing in this file.


Step 2: Case-Insensitive Search (-i)

📸 Verified Output:


Step 3: Show Line Numbers (-n)

📸 Verified Output:

💡 -n is essential when reviewing config files — it shows you exactly which line to go to in your editor: grep -n 'PermitRootLogin' /etc/ssh/sshd_config


Step 4: Inverted Match (-v)

📸 Verified Output:

💡 -v (inVert) prints lines that don't match. Extremely useful for filtering out noise: grep -v '^#' /etc/ssh/sshd_config removes all comment lines.


Step 5: Count Matches (-c)

📸 Verified Output:


Step 6: Extended Regex (-E) — Multiple Patterns

📸 Verified Output:

📸 Verified Output:

💡 -E enables extended regular expressions: | (or), + (one or more), ? (zero or one), {n,m} (repeat). -E is equivalent to the egrep command.


Step 7: grep on System Files

📸 Verified Output:

📸 Verified Output:

📸 Verified Output:


Step 8: Capstone — Log Threat Hunting

📸 Verified Output:


Summary

Option
Meaning

grep 'pattern' file

Basic search

grep -i

Case-insensitive

grep -n

Show line numbers

grep -v

Invert (exclude matches)

grep -c

Count matching lines

grep -E

Extended regex (`

grep -o

Print only the matching part

grep -r

Recursive search in directories

grep -l

Print filenames only

Last updated