Software & OS

grep Command: 15 Practical Examples With Real Output

The grep command prints every line in a file that matches a pattern: grep "error" app.log shows each line of app.log containing "error". Add -i to ignore case, -r to search a whole directory, -n for line numbers, and -v to show lines that don't match.

grep -rni "error" .

That one searches the current directory recursively, case-insensitively, with line numbers. It's the most common combination.

Sample files used in the examples

All output below is real, from GNU grep in Git Bash on Windows, run against two small test files. logs/app.log:

INFO server started on port 8080
WARN disk usage at 91%
ERROR connection refused: db01
error: retrying in 5s
INFO request id=42 completed
ERROR timeout after 30s

And a src/ folder containing db.py and server.js, each with a TODO comment.

1. Search a file for a word

$ grep ERROR logs/app.log
ERROR connection refused: db01
ERROR timeout after 30s

grep is case-sensitive by default, so the line starting with lowercase error: is not shown.

2. Ignore case with -i

$ grep -i error logs/app.log
ERROR connection refused: db01
error: retrying in 5s
ERROR timeout after 30s

3. Show line numbers with -n

$ grep -n TODO src/*
src/db.py:2:    # TODO: add retry
src/server.js:2:// TODO remove debug

With more than one file, grep prefixes each line with the file name. -n adds the line number after it.

4. Search a whole directory with -r

$ grep -r TODO .
./src/db.py:    # TODO: add retry
./src/server.js:// TODO remove debug

The man page explains the difference between the two recursive flags: -r follows symbolic links only if they are named on the command line, while -R follows all of them.

5. List only the file names with -l

$ grep -rl TODO .
./src/db.py
./src/server.js

-L does the opposite and lists files with no match: grep -L TODO logs/app.log src/* prints logs/app.log.

6. Count matching lines with -c

$ grep -c ERROR logs/app.log
2

-c counts lines, not occurrences. A line containing the word twice counts once. To count occurrences, combine -o with wc -l: grep -o ERROR logs/app.log | wc -l.

7. Show lines that don't match with -v

$ grep -v INFO logs/app.log
WARN disk usage at 91%
ERROR connection refused: db01
error: retrying in 5s
ERROR timeout after 30s

Handy for removing noise: grep -v DEBUG on a log, or grep -v '^#' to hide comment lines in a config file.

8. Match whole words only with -w

$ grep -w port src/server.js
const port = process.env.PORT || 3000;
console.log("debug", port);

The man page defines -w as selecting "only those lines containing matches that form whole words". Without it, port would also match report, import and support.

9. Match several patterns with -E

$ grep -E 'ERROR|WARN' logs/app.log
WARN disk usage at 91%
ERROR connection refused: db01
ERROR timeout after 30s

This is the example that trips people up most. Without -E, grep uses basic regular expressions, where | is an ordinary character, so grep 'ERROR|WARN' searches for the literal text ERROR|WARN, prints nothing and exits with status 1. GNU grep accepts \| as the "or" operator in basic mode (grep 'ERROR\|WARN'), and the same goes for \+ and \?. With -E, you write them without backslashes. You can also pass several patterns with repeated -e: grep -e ERROR -e WARN.

10. Search for literal text with -F

$ grep -F '91%' logs/app.log
WARN disk usage at 91%

-F interprets the pattern "as fixed strings, not regular expressions". Use it whenever the text you're searching for contains ., *, [, $ or other regex characters. grep '1.2.3' also matches 1x2y3, because . means "any character"; grep -F '1.2.3' matches only the literal version.

11. Print only the matching part with -o

$ grep -o '[0-9]\+s' logs/app.log
5s
30s

-o prints each match on its own line instead of the whole line. Combine it with sort | uniq -c to get a frequency table:

$ grep -io 'error[^:]*' logs/app.log | sort | uniq -c
      1 ERROR connection refused
      1 ERROR timeout after 30s
      1 error

12. Show lines around each match with -A, -B, -C

$ grep -n -B1 -A1 'connection refused' logs/app.log
2-WARN disk usage at 91%
3:ERROR connection refused: db01
4-error: retrying in 5s

-B1 adds one line before, -A1 one line after, and -C2 two lines on each side. With -n, the matching line uses a colon and context lines use a dash, so you can tell them apart.

13. Limit a recursive search by file type

$ grep -rn --include='*.py' TODO .
./src/db.py:2:    # TODO: add retry

--include searches only files whose base name matches the glob. --exclude skips files, and --exclude-dir skips whole directories, which is useful for node_modules and .git: grep -rn --exclude-dir=node_modules --exclude-dir=.git TODO .. Quote the glob so the shell doesn't expand it first.

14. Use grep in scripts: -q and exit codes

$ grep -q ERROR logs/app.log; echo $?
0
$ grep -q FATAL logs/app.log; echo $?
1
$ grep FATAL nofile.log; echo $?
grep: nofile.log: No such file or directory
2

From the man page: "the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred". -q prints nothing, which makes it the right choice inside if:

if grep -q "ERROR" logs/app.log; then
  echo "errors found"
fi

One subtlety: with -q, if a match is found the exit status is 0 even if an error also occurred (for example, one of several files was missing).

15. Filter another command's output

grep reads standard input when you don't give it a file, so it works as a filter after a pipe:

ps aux | grep nginx
history | grep ssh
docker ps | grep -v Exited
ls -la | grep '^d'

The last one lists only directories, because their permission string starts with d. For finding files by name or size rather than content, use find instead; finding large files shows how.

A note on -P (Perl-compatible regex)

-P enables Perl-style patterns such as \d, \s and lookarounds. The man page notes that this support exists only if grep was built with PCRE enabled, and it can depend on your locale. In the Git Bash used for these examples, grep -P 'id=\d+' logs/app.log refused to run with:

grep: -P supports only unibyte and UTF-8 locales

If -P isn't available, rewrite \d as [0-9] and use -E.

grep equivalents on Windows

PowerShell's Select-String (alias sls) is the closest native equivalent. Microsoft's documentation describes it as similar to grep in Unix or findstr.exe in Windows. It treats the pattern as a regular expression and, unlike grep, is case-insensitive by default:

PS> Select-String -Path logs\app.log -Pattern 'ERROR' -CaseSensitive

logs\app.log:3:ERROR connection refused: db01
logs\app.log:6:ERROR timeout after 30s
grepPowerShell Select-StringCommand Prompt findstr
grep -idefault (use -CaseSensitive for grep's default)/i
grep -v-NotMatch/v
grep -ndefault (line numbers always shown)/n
grep -rGet-ChildItem -Recurse | Select-String/s
grep -l-List (first match per file)/m
grep -F-SimpleMatch/l or /c:"text"
grep -C 2-Context 2not available
grep -q-Quietcheck %ERRORLEVEL%

Watch out for one findstr quirk: spaces separate multiple search strings, so findstr hello there x.y finds lines containing "hello" or "there". Use findstr /c:"hello there" x.y to search for the phrase. The full grep is also available on Windows through Git for Windows or WSL.

Frequently asked questions

How do I grep for a string with spaces?
Put the pattern in quotes so the shell passes it as one argument: grep "connection refused" app.log. Without quotes, grep treats the first word as the pattern and the rest as file names.
How do I search for a pattern that starts with a dash?
Use -e before the pattern, as in grep -e '-v' file.txt, or put -- before it: grep -- '-v' file.txt. Otherwise grep reads the pattern as an option.
Is there grep on Windows?
Not built in, but Git for Windows (Git Bash) and WSL both include GNU grep. Native alternatives are PowerShell's Select-String, which uses regular expressions and is case-insensitive by default, and findstr in Command Prompt.

Sources