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.logShows every line in app.log that contains error. The search is case sensitive.
grep -i "error" app.logIgnores case, so Error and ERROR match too.
grep -n "error" app.logShows the line number in front of each match.
grep -c "error" app.logCounts the matching lines instead of showing them.
grep -v "^#" config.confShows 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.txtMatches cat as a whole word only, so category and concatenate are skipped.
grep -E "error|warning" app.logMatches lines containing error or warning. -E turns on extended patterns.
grep -A 2 -B 1 "error" app.logShows 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 | headCounts the visits from each IP address in a web server log, busiest first.
Quick reference
| Option | Meaning |
|---|---|
-i | Ignore upper and lower case |
-n | Show line numbers |
-c | Count matching lines |
-v | Show lines that do not match |
-r | Search all files in a directory |
-l | List file names only |
-w | Match whole words |
-E | Extended patterns, such as a|b |
-A / -B | Lines after / before each match |