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

First, create practice files for the grep examples:

Create a notes file with various text including "hello":

cat > notes.txt << 'EOF'
Hello, welcome to the notes file.
This file contains various information.
hello there, how are you?
Some lines have HELLO in uppercase.
Other lines have Hello with capital H.
This line doesn't have hello at all.
EOF

Create a log file with error and success messages:

cat > log.txt << 'EOF'
2024-01-01 10:00:00 System started successfully
2024-01-01 10:05:23 error: Connection failed
2024-01-01 10:10:45 User logged in successfully
2024-01-01 10:15:12 error: File not found
2024-01-01 10:20:30 Request processed successfully
2024-01-01 10:25:55 error: Timeout occurred
2024-01-01 10:30:18 Operation completed successfully
2024-01-01 10:35:42 System status OK
EOF

Create multiple text files for searching:

cat > file1.txt << 'EOF'
This is an important document.
It contains important information.
Some lines are not important.
EOF
cat > file2.txt << 'EOF'
Another file with some text.
This file has important notes.
Regular text here.
EOF
cat > file3.txt << 'EOF'
This file doesn't have the word.
Just regular content here.
Nothing special in this file.
EOF

Create a Python code file for line number examples:

cat > code.py << 'EOF'
def calculate_total(items):
    total = 0
    for item in items:
        total += item.price
    return total

# There's a bug in this function
def process_data(data):
    result = []
    for d in data:
        # Bug: missing validation
        result.append(d.value)
    return result

def main():
    print("Starting program")
    # No bug here
    print("Program complete")
EOF

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