Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

grep Command Guide for Searching Text

This guide helps you understand and use the grep command, the standard way to find lines matching a pattern inside text.


What is grep, and Why Use It?

The grep command searches one or more files (or a stream) for lines matching a pattern, and prints every line that matches. The name comes from the old ed editor command g/re/p — “global, regular expression, print.”

Why Learn grep?

  • Find anything in logs: Spot errors, usernames, or IP addresses in files with thousands of lines.
  • Filter command output: ls output, process lists, command help — anything can be piped through grep.
  • It’s everywhere: Scripts, config audits, security checks — grep is the first tool most sysadmins reach for.
  • Patterns scale: What starts as “find this word” grows into full regular expressions that describe shapes of text.

If you learn only one command from this section, make it grep. It is the most-used text tool in existence.


1. Search a Single File

grep "error" /var/log/syslog
  • Prints every line in the file containing the word error.
  • The match is highlighted in color when output goes to a terminal.

Example:

grep "error" /var/log/syslog
error: disk full on /dev/sda1
error: cannot open config file

2. Search Multiple Files

grep "error" /var/log/syslog /var/log/kern.log
  • When searching more than one file, grep prefixes each match with the filename.

Tip: search every file in a directory with a glob:

grep "TODO" src/*.md

3. Search a Whole Directory Recursively

grep -r "TODO" src/
  • -r (recursive) descends into every file under the directory.
  • This is the most common form of grep in daily work.
FlagEffect
-rSearch directories recursively.
-lList only the names of files containing a match.
-LList only files that do not contain a match.
-cPrint a count of matching lines per file.
-nPrint line numbers along with matches.

Example — which files mention a setting, and how often?

grep -rc "timeout" /etc/nginx/

grep -i "error" file.txt
  • -i ignores case, so Error, ERROR, and error all match.
grep -v "debug" file.txt
  • -v inverts the match: print every line that does not match. Useful for stripping out noise:
grep -v "^#" config.txt

That prints the config without comment lines.


5. Whole Words, Context, and Colors

grep -w "cat" file.txt
  • -w matches whole words only, so cat no longer matches concatenate.

Context around each match:

grep -B 2 -A 2 "panic" kernel.log
  • -B 2 prints 2 lines Before each match, -A 2 prints 2 lines After.
  • -C 3 prints 3 lines both before and after.

Force colored output when piping to another command:

grep --color=always "error" file.txt | less -R

6. Regular Expressions

grep accepts three levels of pattern matching:

grep "user[0-9]" file.txt        # basic: digit ranges
grep -E "user[0-9]+" file.txt    # extended: one-or-more, groups, alternation
PatternMatches
.Any single character.
*Zero or more of the previous character.
^Start of line.
$End of line.
[abc]Any one character in the set.
[^abc]Any one character not in the set.
| (with -E)Alternation: this or that.

Examples:

grep -E "^(alice|bob):" /etc/passwd    # users alice or bob
grep -E "^[0-9]{3}-[0-9]{4}" data.txt  # phone-number-like lines
grep "error$" file.txt                  # lines ending in 'error'

7. Search for Literal Patterns and Binary Files

grep -F "192.168.1.1*" file.txt
  • -F treats the pattern as a fixed string, not a regex — faster and safer when your pattern contains characters like . or *.
grep -I "pattern" *
  • -I skips binary files entirely (the uppercase i). Without it, grep on a binary prints “Binary file … matches” instead of the lines.

8. Combine with Pipes

grep shines when filtering the output of other commands:

ps aux | grep "nginx"
ls -l | grep -c "^-"

That counts regular files in a listing. The classic anti-pattern ps aux | grep foo also matches the grep itself — use pgrep instead when you only want process IDs (see ps in the processes section).


Common Pitfalls

  • Forgetting to quote patterns with spaces or special characters. grep error: file not found fails; write grep "error" file.txt.
  • Confusing regex and literal matching. grep "file.txt" treats . as “any character”. Use -F for literal strings.
  • grep matches substrings by default. Searching for cat also finds concatenate. Add -w for whole words.
  • Case surprises. grep Error misses error. Use -i unless case matters.
  • Binary files silently matching. Add -I or --binary-files=without-match when searching everything under a directory.

PageRelationship
sedEdits and replaces text instead of just finding it.
awkAnalyzes structured columns instead of matching whole lines.
pipes.mdHow grep receives data from other commands.
egrep/fgrepLegacy names for grep -E and grep -F.

grep Cheatsheet

CommandWhat It Does
grep "word" filePrint lines containing word.
grep -r "word" dir/Search a directory recursively.
grep -i "word" fileCase-insensitive search.
grep -v "word" filePrint lines that do not match.
grep -n "word" fileShow line numbers.
grep -c "word" fileCount matching lines.
grep -l "word" *List only filenames with matches.
grep -w "word" fileWhole-word match only.
grep -E "a|b" fileExtended regex: a or b.
grep -F "str" fileTreat pattern as a literal string.
grep -A3 -B3 "x" fShow 3 lines of context around matches.
grep -I "word" *Skip binary files.