Skip to content

Text searching with grep

grep stands for Global Regular Expression Print. It’s a command-line utility that searches for lines that match a pattern.

Use cases

Searches for "pattern" in file.txt and prints every matching line

grep "pattern" file.txt

Finds "hello", "Hello", "HELLO", etc

grep -i "hello" greetings.txt

View line numbers

Adds line numbers to the matching lines

grep -n "main" script.py

Exclude lines (inverse match)

Shows every line except the ones with "DEBUG"

grep -v "DEBUG" logs.txt

Search all files in a directory

Recursively search for "error" in all files under ./src

grep -r "error" ./src

Match exact words

Matches only the word "cat", not "catalog" or "educate"

grep -w "cat" animals.txt

Highlight

grep --color=auto "foo" file.txt

Find files

grep -l "TODO" *.js

Search with regular expressions

grep -E "dog|cat" animals.txt