grep Cheatsheet

This overview summarizes the grep commands I frequently use to search for text in files.

Bash
grep "pattern" file.txt
# searches for the pattern in file.txt

grep -i "pattern" file.txt
# ignores case (case-insensitive search)

grep -R "pattern" /path
# searches recursively in all files under /path for the pattern [pattern]

grep -n "pattern" *.txt
# shows matching lines with line numbers

grep -v "^#" file.txt
# shows all lines that do not start with # (filters out comments)

grep -c "pattern" file.txt
# counts the number of matches; if a directory is given, returns one count per file

grep -l "pattern" /path
# lists each file that contains the pattern

grep -w "pattern" file.txt
# matches as a whole word

grep --color=auto "pattern" file.txt
# highlights matches in color

grep -A 2 "pattern" file.txt
# shows 2 lines **after** each match

grep -B 2 "pattern" file.txt
# shows 2 lines **before** each match

grep -C 2 "pattern" file.txt
# shows 2 lines **before and after** each match

grep -E "pattern1|pattern2|pattern3" file.txt
# shows all lines containing at least one of the patterns [pattern*]

grep "pattern1" file.txt | grep "pattern2" | grep "pattern3"
# shows only lines that match **all 3** patterns (logical AND)

awk '/pattern1/ && /pattern2/ && /pattern3/' file.txt
# alternative to the above, with case sensitivity

grep -Rin "pattern" /path
# recursive, case-insensitive, shows line numbers

grep -Ril "pattern" /path
# recursive, case-insensitive, shows only filenames

Comments

Leave a Reply