GNU grep
Cheatsheet
#
GNU grep is a widely-used version of the grep command, developed as part of the GNU Project. It is the default grep implementation on many Linux distributions and provides a comprehensive set of features for text searching and processing. GNU grep extends the functionality of traditional grep with additional options like Perl-compatible regular expressions (-P), colorized output (–color=auto), and enhanced support for extended regular expressions.
Basic Usage
#
Command | Description |
---|
grep 'pattern' file.txt | Search for a pattern in a file |
grep 'pattern' file1.txt file2.txt file3.txt | Search for a pattern in multiple files |
grep -r 'pattern' directory/ | Search recursively in directories |
grep -R 'pattern' directory/ | Same as -r but also follows symbolic links (recursive) |
Common Options
#
Command | Description |
---|
grep -i 'pattern' file.txt | Case-insensitive search |
grep -n 'pattern' file.txt | Display line numbers with output |
grep -l 'pattern' *.txt | Display only the names of files with matching lines |
grep -L 'pattern' *.txt | Display files that do not match the pattern |
grep -c 'pattern' file.txt | Count the number of matching lines |
grep -B 3 'pattern' file.txt | Show lines before matches (3 lines before) |
grep -A 3 'pattern' file.txt | Show lines after matches (3 lines after) |
grep -C 3 'pattern' file.txt | Show context around matches (3 lines before and after) |
Extended Regular Expressions
#
Command | Description |
---|
grep -E 'pattern1|pattern2' file.txt | Use extended regular expressions |
grep '^pattern' file.txt | Match lines starting with a pattern |
grep 'pattern$' file.txt | Match lines ending with a pattern |
grep -w 'pattern' file.txt | Match whole words only |
grep -v 'pattern' file.txt | Invert match (show lines that do not match) |
grep -o 'pattern' file.txt | Display only the matched part of the line |
grep -H 'pattern' file.txt | Display the matched line along with the file name |
grep -m 5 'pattern' file.txt | Show only a specific number of matching lines |
grep --color=auto 'pattern' file.txt | Colorize the matching pattern |
grep -P 'pattern' file.txt | Use Perl-compatible regular expressions |