Zsh Shell Tutorial #17: Master grep for Text Searching
Video: Zsh Shell Tutorial #17: Master grep for Text Searching by Taught by Celeste AI - AI Coding Coach
Watch full page →Zsh Shell Tutorial #17: Master grep for Text Searching
grep is a powerful command-line tool used in Zsh for searching text patterns within files and outputs. This tutorial covers essential grep features including case-insensitive searches, line numbering, regular expressions, recursive directory searching, and filtering by file types to help you efficiently locate information in your files.
Code
# Basic pattern search in a file
grep "pattern" filename.txt
# Case-insensitive search
grep -i "pattern" filename.txt
# Show line numbers with matches
grep -n "pattern" filename.txt
# Count the number of matching lines
grep -c "pattern" filename.txt
# Invert match to show lines NOT containing the pattern
grep -v "pattern" filename.txt
# Use anchors: ^ for start, $ for end of line
grep "^start" filename.txt # lines starting with 'start'
grep "end$" filename.txt # lines ending with 'end'
# Wildcard '.' matches any single character
grep "a.b" filename.txt # matches 'a' followed by any char, then 'b'
# Character classes: digits and lowercase letters
grep "[0-9]" filename.txt # lines containing any digit
grep "[a-z]" filename.txt # lines containing any lowercase letter
# Extended regex with -E for alternation, +, ?
grep -E "cat|dog" filename.txt # lines containing 'cat' or 'dog'
grep -E "go+" filename.txt # 'g' followed by one or more 'o's
# Recursive search in directories
grep -r "pattern" /path/to/dir
# Show 2 lines of context after matches
grep -A 2 "pattern" filename.txt
# Show 2 lines of context before matches
grep -B 2 "pattern" filename.txt
# Show 2 lines of context before and after matches
grep -C 2 "pattern" filename.txt
# Filter files by extension during recursive search
grep -r --include="*.log" "error" /var/logs
# Exclude certain files during recursive search
grep -r --exclude="*.tmp" "pattern" /path/to/dir
# Pipe output of a command to grep
ps aux | grep "process_name"
Key Points
- Use grep with simple patterns or powerful regular expressions to search text in files and outputs.
- Flags like -i, -n, and -v enable case-insensitive search, line numbering, and inverted matching respectively.
- Extended regex (-E) allows complex pattern matching with alternation and quantifiers.
- Recursive search (-r) combined with --include/--exclude filters lets you target specific file types in directories.
- Piping commands to grep is essential for filtering process lists or command outputs efficiently.