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
#
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 |
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 'pattern' file.txt | Colorize the matching pattern |
grep -P 'pattern' file.txt | Use Perl-compatible regular expressions |