Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views6 pages

Grep Manual

The GREP Instructional Manual provides a comprehensive guide to using the grep command-line utility for searching text patterns in files. It covers basic syntax, common commands, options, regular expressions, practical examples, and advanced usage tips. The manual also includes a quick reference section for common use cases and regex patterns.

Uploaded by

kjbrian90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Grep Manual

The GREP Instructional Manual provides a comprehensive guide to using the grep command-line utility for searching text patterns in files. It covers basic syntax, common commands, options, regular expressions, practical examples, and advanced usage tips. The manual also includes a quick reference section for common use cases and regex patterns.

Uploaded by

kjbrian90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

================================================================================

GREP INSTRUCTIONAL MANUAL


A Comprehensive Guide to Using grep
================================================================================

TABLE OF CONTENTS
-----------------
1. Introduction to grep
2. Basic Syntax
3. Basic grep Commands
4. Common Options
5. Regular Expression Patterns
6. Practical Examples
7. Advanced Usage
8. Tips and Best Practices
9. Quick Reference

================================================================================
1. INTRODUCTION TO GREP
================================================================================

grep (Global Regular Expression Print) is a powerful command-line utility for


searching text patterns in files. It searches for patterns in files and prints
matching lines to standard output.

Key Features:
- Search text files for patterns
- Support for regular expressions
- Can search multiple files
- Recursive directory searching
- Case-sensitive and case-insensitive searching
- Line numbering and context display

================================================================================
2. BASIC SYNTAX
================================================================================

The basic grep syntax is:

grep [OPTIONS] PATTERN [FILE...]

Where:
- OPTIONS: Command flags that modify grep's behavior
- PATTERN: The text or regular expression to search for
- FILE: One or more files to search (if omitted, reads from stdin)

Basic Examples:
grep "hello" file.txt # Search for "hello" in file.txt
grep "error" *.log # Search for "error" in all .log files
cat file.txt | grep "pattern" # Search stdin for "pattern"

================================================================================
3. BASIC GREP COMMANDS
================================================================================

These are the essential grep commands every user should know:

1. Simple text search:


grep "pattern" filename
Example: grep "error" log.txt

2. Case-insensitive search:
grep -i "pattern" filename
Example: grep -i "WARNING" log.txt # finds WARNING, warning, Warning, etc.

3. Search multiple files:


grep "pattern" file1 file2 file3
grep "pattern" *.txt
Example: grep "TODO" *.py # search all Python files

4. Show line numbers:


grep -n "pattern" filename
Example: grep -n "function" script.js

5. Count matches:
grep -c "pattern" filename
Example: grep -c "failed" test-results.log

6. Show only filenames with matches:


grep -l "pattern" *.txt
Example: grep -l "import" *.py # list Python files containing "import"

7. Invert match (show lines NOT containing pattern):


grep -v "pattern" filename
Example: grep -v "debug" log.txt # show all lines except those with "debug"

8. Match whole words only:


grep -w "word" filename
Example: grep -w "main" code.c # matches "main" but not "mainly"

9. Recursive search in directories:


grep -r "pattern" directory/
Example: grep -r "TODO" ./src/

10. Show context around matches:


grep -A 2 "pattern" filename # 2 lines after
grep -B 2 "pattern" filename # 2 lines before
grep -C 2 "pattern" filename # 2 lines before and after

Common Combinations:
# Case-insensitive recursive search with line numbers
grep -irn "error" ./logs/

# Count occurrences in all text files


grep -c "pattern" *.txt

# Find files containing pattern but exclude some


grep -r "TODO" . --exclude="*.pyc"

# Pipe from other commands


ps aux | grep "python"
history | grep "git"
cat file.txt | grep "search"

Quick Examples You Can Try:


# Search for your username in /etc/passwd
grep "$USER" /etc/passwd
# Find all lines starting with "#" (comments)
grep "^#" ~/.zshrc

# Find all lines ending with ";"


grep ";$" script.js

# Search for lines containing numbers


grep "[0-9]" data.txt

================================================================================
4. COMMON OPTIONS
================================================================================

-i, --ignore-case Case-insensitive search


-v, --invert-match Show lines that DON'T match the pattern
-n, --line-number Show line numbers with output
-c, --count Count matching lines instead of showing them
-l, --files-with-matches Show only filenames with matches
-L, --files-without-match Show only filenames without matches
-r, --recursive Search directories recursively
-w, --word-regexp Match whole words only
-x, --line-regexp Match whole lines only
-A NUM, --after-context=NUM Show NUM lines after match
-B NUM, --before-context=NUM Show NUM lines before match
-C NUM, --context=NUM Show NUM lines before and after match
-E, --extended-regexp Use extended regular expressions (ERE)
-F, --fixed-strings Treat pattern as literal string, not regex
-h, --no-filename Don't show filenames in output
-H, --with-filename Show filenames in output (default for multiple files)
--color=auto Highlight matches in color

================================================================================
5. REGULAR EXPRESSION PATTERNS
================================================================================

Basic Regular Expressions (BRE):


. Any single character
* Zero or more of the preceding character
^ Beginning of line
$ End of line
\ Escape character
[] Character class
[^] Negated character class

Extended Regular Expressions (ERE) - use with -E:


+ One or more of the preceding character
? Zero or one of the preceding character
| Alternation (OR)
() Grouping
{} Repetition count

Character Classes:
[abc] Match any of a, b, or c
[a-z] Match any lowercase letter
[A-Z] Match any uppercase letter
[0-9] Match any digit
[^0-9] Match any non-digit

Special Character Classes:


\w Word character (alphanumeric + underscore)
\W Non-word character
\d Digit
\D Non-digit
\s Whitespace
\S Non-whitespace

================================================================================
6. PRACTICAL EXAMPLES
================================================================================

Basic Searches:
grep "error" app.log # Find all lines with "error"
grep -i "warning" *.txt # Case-insensitive search
grep -n "TODO" script.py # Show line numbers
grep -c "failed" test.log # Count failures

Pattern Matching:
grep "^Error:" log.txt # Lines starting with "Error:"
grep "\.txt$" filelist # Lines ending with ".txt"
grep "[0-9]\{3\}-[0-9]\{4\}" data # Match phone patterns (xxx-xxxx)
grep -E "cat|dog" pets.txt # Match "cat" OR "dog"

File and Directory Searches:


grep -r "function" ./src # Recursive search in src/
grep -l "import" *.py # List Python files with imports
grep -L "copyright" *.c # C files without copyright

Context Display:
grep -A 3 "ERROR" app.log # Show 3 lines after each match
grep -B 2 "CRITICAL" system.log # Show 2 lines before each match
grep -C 1 "Exception" debug.log # Show 1 line before and after

Advanced Patterns:
grep -E "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$" emails.txt
# Match email addresses

grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" network.log


# Match IP addresses

grep -w "main" *.c


# Match whole word "main" (not "mainly" or "domain")

================================================================================
7. ADVANCED USAGE
================================================================================

Combining with Other Commands:


ps aux | grep "python" # Find Python processes
history | grep "git" # Search command history
find . -name "*.txt" -exec grep "pattern" {} \; # Search in found files

Using grep in Scripts:


if grep -q "error" logfile; then
echo "Errors found!"
fi

Multiple Patterns:
grep -e "pattern1" -e "pattern2" file # Match either pattern
grep -f patterns.txt data.txt # Read patterns from file

Excluding Patterns:
grep "log" file | grep -v "debug" # Find "log" but not "debug"
grep -r --exclude="*.pyc" "import" . # Exclude .pyc files
grep -r --exclude-dir=".git" "TODO" . # Exclude .git directory

Performance Tips:
grep -F "literal string" huge.txt # Faster for literal strings
LC_ALL=C grep "pattern" file # Faster for ASCII-only

================================================================================
8. TIPS AND BEST PRACTICES
================================================================================

1. Use quotes around patterns to avoid shell interpretation


Good: grep "file*.txt" data
Bad: grep file*.txt data

2. Use -F for literal string searches (faster than regex)


grep -F "http://example.com" logs.txt

3. Combine grep commands for complex filtering


grep "error" log | grep -v "debug" | grep "critical"

4. Use --color=auto for easier visual scanning


alias grep='grep --color=auto'

5. Be careful with special characters - escape them


grep "\$100" prices.txt # Search for literal "$100"

6. Use -q for scripts (quiet mode, check exit status)


if grep -q "SUCCESS" result.log; then echo "Test passed"; fi

7. Remember grep is line-oriented


- It processes one line at a time
- Multi-line patterns require special handling

8. Use appropriate tools for specific tasks


- awk/sed for complex text processing
- find for file searching
- ripgrep (rg) or silver searcher (ag) for faster searches

================================================================================
9. QUICK REFERENCE
================================================================================

Common Use Cases:


grep "pattern" file # Basic search
grep -i "pattern" file # Case-insensitive
grep -r "pattern" . # Recursive search
grep -n "pattern" file # With line numbers
grep -v "pattern" file # Inverse match
grep -c "pattern" file # Count matches
grep -l "pattern" *.txt # List matching files
grep -w "word" file # Whole word match
grep -A2 -B2 "pattern" file # Show context
grep -E "pat1|pat2" file # Multiple patterns (OR)
grep "^start" file # Lines starting with
grep "end$" file # Lines ending with
grep "[0-9]" file # Contains digit
grep -f patterns.txt data.txt # Patterns from file

Exit Status:
0 - Match found
1 - No match found
2 - Error occurred

Common Regex Patterns:


Email: [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}
IP: ([0-9]{1,3}\.){3}[0-9]{1,3}
URL: https?://[^\s]+
Phone: \([0-9]{3}\) [0-9]{3}-[0-9]{4}
Date: [0-9]{4}-[0-9]{2}-[0-9]{2}

================================================================================
END OF MANUAL
================================================================================

For more information, consult the grep man page: man grep

You might also like