grep

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 #

CommandDescription
grep 'pattern' file.txtSearch for a pattern in a file
grep 'pattern' file1.txt file2.txt file3.txtSearch 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 #

CommandDescription
grep -i 'pattern' file.txtCase-insensitive search
grep -n 'pattern' file.txtDisplay line numbers with output
grep -l 'pattern' *.txtDisplay only the names of files with matching lines
grep -L 'pattern' *.txtDisplay files that do not match the pattern
grep -c 'pattern' file.txtCount the number of matching lines
grep -B 3 'pattern' file.txtShow lines before matches (3 lines before)
grep -A 3 'pattern' file.txtShow lines after matches (3 lines after)
grep -C 3 'pattern' file.txtShow context around matches (3 lines before and after)

Extended Regular Expressions #

CommandDescription
grep -E 'pattern1|pattern2' file.txtUse extended regular expressions
grep '^pattern' file.txtMatch lines starting with a pattern
grep 'pattern$' file.txtMatch lines ending with a pattern
grep -w 'pattern' file.txtMatch whole words only
grep -v 'pattern' file.txtInvert match (show lines that do not match)
grep -o 'pattern' file.txtDisplay only the matched part of the line
grep -H 'pattern' file.txtDisplay the matched line along with the file name
grep -m 5 'pattern' file.txtShow only a specific number of matching lines
grep --color=auto 'pattern' file.txtColorize the matching pattern
grep -P 'pattern' file.txtUse Perl-compatible regular expressions

grep

Explore our comprehensive cheatsheets to enhance your knowledge and efficiency. Each cheatsheet provides detailed command options, examples, and descriptions to help you master various tools and technologies.