Linux grep Command: Search Inside Files

grep searches text for lines that match a word or pattern. Use it to find an error in a log file, a setting in a config file, or every file in a folder that mentions something.

Basic searches

grep "error" app.log
Shows every line in app.log that contains error. The search is case sensitive.
grep -i "error" app.log
Ignores case, so Error and ERROR match too.
grep -n "error" app.log
Shows the line number in front of each match.
grep -c "error" app.log
Counts the matching lines instead of showing them.
grep -v "^#" config.conf
Shows the lines that do not match. Here it hides comment lines starting with #.

Searching many files

grep -r "TODO" .
Searches every file in the current directory and below.
grep -rl "TODO" .
Lists only the names of the files that contain a match.
grep -r --include="*.php" "TODO" .
Searches only files ending in .php.

Better matching

grep -w "cat" pets.txt
Matches cat as a whole word only, so category and concatenate are skipped.
grep -E "error|warning" app.log
Matches lines containing error or warning. -E turns on extended patterns.
grep -A 2 -B 1 "error" app.log
Shows 1 line before and 2 lines after each match, so you can see what happened around it.

Combining with other commands

grep is often used after a pipe (|) to filter the output of another command.

ls /etc | grep -i "conf"
Lists only the entries in /etc with conf in the name.
grep -oE "^[0-9.]+" access.log | sort | uniq -c | sort -rn | head
Counts the visits from each IP address in a web server log, busiest first.

Quick reference

OptionMeaning
-iIgnore upper and lower case
-nShow line numbers
-cCount matching lines
-vShow lines that do not match
-rSearch all files in a directory
-lList file names only
-wMatch whole words
-EExtended patterns, such as a|b
-A / -BLines after / before each match