CIS120 Linux Fundamentals by Scott Shaper

The grep Command

Think of grep as your text search superpower in Linux. It's like having a super-fast "Find" feature that can search through files, directories, and even output from other commands. The name "grep" comes from "global regular expression print," but don't worry about that for now - just think of it as your go-to tool for finding text in files.

Why Learn grep?

The grep command is essential because:

Basic Syntax

grep [options] "what to search for" [where to search]

Common Options

Option What It Does When to Use It
-i Ignores uppercase/lowercase differences When you're not sure about capitalization
-v Shows lines that DON'T match When you want to exclude certain text
-r Searches through folders and subfolders When you need to search an entire directory
-l Shows only filenames with matches When you just want to know which files contain the text
-n Shows line numbers with matches When you need to find where matches occur
-c Counts how many times text appears When you want to know how often something occurs
-w Matches whole words only When you want to avoid partial matches
-A Shows lines after the match When you need to see what comes after
-B Shows lines before the match When you need to see what came before
-C Shows lines around the match When you need context around the match

Practical Examples

Basic Search

To find a word in a file:

grep "hello" notes.txt

This shows all lines in notes.txt that contain the word "hello".

Case-Insensitive Search

To find text regardless of uppercase/lowercase:

grep -i "hello" notes.txt

This finds "hello", "Hello", "HELLO", etc.

Finding What's Not There

To find lines that don't contain certain text:

grep -v "error" log.txt

This shows all lines in log.txt that don't contain the word "error".

Searching Multiple Files

To search through all text files in a directory:

grep "important" *.txt

This looks for "important" in all files ending with .txt.

Searching with Line Numbers

To see where matches occur:

grep -n "bug" code.py

This shows each match with its line number, like "42: bug in this line".

Counting Matches

To count how many times something appears:

grep -c "success" log.txt

This tells you how many lines contain the word "success".

Searching with Context

To see what's around your matches:

grep -C 2 "error" log.txt

This shows the matching line plus 2 lines before and after it.

Tips for Success

Common Mistakes to Avoid

Best Practices