Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

grep searches input for lines that match a pattern and prints those lines. The 16 examples below show the decisions that matter in practice: literal text or a regular expression, one file or a directory tree, and full lines or a focused result such as a count, filename, or context. Commands use GNU grep syntax; other implementations can differ, especially for long options and PCRE support.

GNU grep uses basic regular expressions by default. Use -F when the text must be taken literally, -E for extended regular expressions, and quote patterns so the shell passes them to grep unchanged. Unless a recursive option changes the behavior, grep reads standard input when you do not name a file.

Choose the right grep mode

Need Typical form What it does
Literal text grep -F 'price: $5.00' file Treats every character as ordinary text.
Basic regular expression grep 'pattern' file GNU grep’s default regular-expression syntax.
Extended regular expression grep -E 'one|two' file Adds convenient operators such as alternation.
PCRE-style expression grep -P 'pattern' file Requests Perl-compatible matching in GNU grep; do not assume it exists on another implementation.

16 practical grep command examples

1. Find a simple string

grep 'ERROR' app.log

This prints every line in app.log containing ERROR. Although the example is a literal-looking word, grep still interprets the pattern as a basic regular expression.

2. Ignore case

grep -i 'error' app.log

-i matches case variations such as Error, ERROR, and error. Use it when capitalization is not meaningful.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Search for punctuation literally

grep -F 'price: $5.00' app.log

-F makes the pattern fixed text, so characters such as $ and . are not interpreted as regular-expression operators. It is usually the clearest choice for an exact snippet copied from a log.

4. Match a whole word

grep -w 'cat' notes.txt

GNU grep’s -w applies its documented word-constituent rules, so cat is not selected inside concatenate. This is a boundary test, not a universal linguistic definition of a word; check the behavior when punctuation or non-ASCII text is important.

5. Match either of two alternatives

grep -E 'ERROR|FATAL' app.log

-E enables extended regular expressions. The alternation operator selects lines containing either ERROR or FATAL. For a larger set of alternatives, keep the expression quoted and group it where necessary.

6. Anchor a pattern at the start of a line

grep '^2026-' app.log

The caret anchors the match to the beginning of each line, so this finds lines whose prefix is 2026-. Replace that prefix with the actual marker used by your file.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

7. Show line numbers

grep -n 'timeout' app.log

-n adds a one-based line number to each matching line. It is useful when you need to open the file at the reported location or cite a precise line in a diagnostic.

8. Print only the matching text

grep -oE '[0-9]{3}-[0-9]{4}' contacts.txt

With GNU grep, -o prints each nonempty matched portion on its own output line. Combined with -E, this extracts phone-number-shaped text instead of printing the surrounding line. It reports matches, not a validation guarantee for the entire file.

9. Count matching lines

grep -c 'WARN' app.log

-c prints the number of selected lines for each input file. If a line contains WARN several times, it still contributes one to the count.

10. Print lines that do not match

grep -v 'DEBUG' app.log

-v inverts selection, printing lines that lack DEBUG. This is useful for removing routine noise from a stream, but remember that blank lines and unrelated messages also pass through.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

11. List only filenames with a match

grep -l 'main' ./*.c

-l stops after finding a match in each file and prints the filename rather than matching content. The shell expands ./*.c before grep runs; that filename glob is separate from grep’s regular-expression syntax.

12. Show surrounding context

grep -C 2 'Exception' app.log

-C 2 prints two lines before and two after each selected line. Use -B 2 for before-only context or -A 2 for after-only context when a smaller window is easier to read.

13. Search a directory tree

grep -r -n 'TODO' ./project

-r recursively descends from ./project, while -n retains line numbers. Review the directory scope before running a broad search; generated files and vendor trees can produce substantial output.

14. Restrict recursive search to a file type

grep -r -n --include='*.c' 'main' ./src

GNU grep’s --include limits recursive traversal results to names matching the supplied shell-style filename pattern. The pattern *.c is a filename filter, not a grep regular expression. Long options such as this one are GNU-specific; verify support on another system.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

15. Filter another command’s output

journalctl -u example.service | grep -i 'failed'

With no filename argument, grep reads standard input, so a pipeline keeps only lines containing failed in any case. journalctl is available on systems using systemd; substitute the command that produces the output you need to inspect.

16. Safely handle a pattern that begins with a hyphen

grep -e "$pattern" ./*

-e explicitly marks the next argument as a pattern, preventing a value such as -WARN from being parsed as an option. The ./* prefix keeps expanded filenames from looking like options. GNU grep also documents -- as an option terminator; use the form appropriate to your filenames, including the edge case of a file literally named -.

Make grep useful in scripts

GNU grep normally exits with status 0 when it selected at least one line, 1 when it selected none, and 2 when an error occurred. A no-match result is therefore different from a failed search. In shell scripts that use set -e, handle the expected no-match case explicitly instead of letting status 1 abort the script.

if grep -q -F 'READY' app.log; then
    echo "ready"
elif [ "$?" -eq 1 ]; then
    echo "not found"
else
    echo "grep error" >&2
    exit 2
fi

-q suppresses normal output and succeeds as soon as a match is found. GNU grep documents a special case: with -q, a match can produce status 0 even if an error was also detected, so do not use quiet mode when you must audit every read error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Portability and pattern safety

  • Use basic or POSIX-compatible options when a command must run across different grep implementations. GNU long options such as --include and GNU-specific -P are not portable defaults.
  • Quote patterns: grep -E 'a[0-9]+b' file. Without quotes, the shell may expand characters before grep receives them.
  • Choose -F for copied text containing punctuation; choose a regular expression only when you need pattern structure.
  • Do not confuse shell globs such as *.c with grep expressions. A glob selects filenames; grep’s pattern selects text within each file.
  • For unusual word boundaries, locales, or non-ASCII data, test the exact input rather than assuming -w matches human-language words.

Troubleshooting common failures

No output, but you expected a match

Check capitalization and try -i. If the text contains punctuation, try -F. Confirm that the file path is correct and that the pattern is not being altered by the shell. A valid no-match search returns status 1, not an execution error.

The command says the pattern is an option

If the pattern can begin with -, pass it with -e. If filenames can begin with a hyphen, use paths such as ./file or an option terminator where supported.

Recursive search is too noisy

Narrow the root directory and add a GNU --include filter, or compose find with grep when you need exact path, size, or exclusion rules. Inspect generated and dependency directories before searching the whole tree.

-P is rejected

PCRE-style matching is a GNU grep request, not a portable guarantee. Rewrite the expression using basic or extended syntax, or use the regular-expression engine documented by the grep implementation installed on the target system.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A script treats “not found” as an error

Branch on grep’s status values. Reserve status 2 for an actual error and treat status 1 according to the script’s logic.

Or skip the browser setup

If your workflow also needs screenshots of the pages referenced in logs, ScreenshotNeo provides a single HTTP request that returns a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners like a visitor, removes more than 60 known consent platforms plus newsletter popups and chat widgets before capture, and bills only clean shots; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for the full option set, including viewport and device presets, full-page and selector captures, dark mode, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous webhooks, bulk capture, usage, and the OpenAPI specification.

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

FAQ

Does grep search inside binary files?

Behavior depends on the implementation and detected file contents; for dependable automation, identify text inputs explicitly and check the target implementation’s manual before processing binary data.

Can one command search several patterns?

Yes. Use an extended expression such as grep -E 'ERROR|FATAL|PANIC' app.log, or supply multiple patterns with options documented by your implementation when maintaining a larger pattern set.

Why does output from several files include filenames?

When grep receives more than one input file, it prefixes matching lines with their filenames so you can identify the source. Use -h to suppress that prefix or -H to request it explicitly where supported.

Frequently Asked Questions

Does grep search inside binary files?

Behavior depends on the implementation and detected file contents; for dependable automation, identify text inputs explicitly and check the target implementation’s manual before processing binary data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can one command search several patterns?

Yes. Use an extended expression such as grep -E 'ERROR|FATAL|PANIC' app.log, or supply multiple patterns with options documented by your implementation when maintaining a larger pattern set.

Why does output from several files include filenames?

When grep receives more than one input file, it prefixes matching lines with their filenames so you can identify the source. Use -h to suppress that prefix or -H to request it explicitly where supported.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.