grep

BSD grep Cheatsheet #

BSD grep is a command-line utility for searching plain-text data sets for lines that match a pattern. Originally part of the Berkeley Software Distribution (BSD), this version of grep is commonly found in BSD-based operating systems such as FreeBSD, OpenBSD, and NetBSD. BSD grep offers an extensive set of features for pattern matching and text processing. It provides options for case-insensitive searches, recursive directory searches, and various ways to control the output format, but it may lack some of the more advanced features found in GNU grep.

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

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 'pattern' file.txtColorize the matching pattern
grep -P 'pattern' file.txtUse Perl-compatible regular expressions

Cheatsheet Website

Discover our extensive collection of cheatsheets covering various tools and technologies to streamline your workflow.