October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

grep Command: Search Files and Output from the Linux Shell

A practical grep command guide covering basic searches, line numbers, case handling, fixed strings, regular expressions, recursive trees, pipelines, and shell-script exit codes.
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 the selected lines. Use a literal search with -F, regular expressions with the default basic mode or -E, and recursive options such as -r when you need to search a directory tree.

What grep does

GNU describes grep as a pattern-matching program: given one or more patterns, it searches input files for matches. In its normal mode, the result is each complete input line containing a match—not just the matching word or substring.

The general form is:

grep [option]... [patterns] [file]...

The pattern and file names are separate operands. If you omit a file, grep reads standard input, so it can filter another command’s output. Quote patterns in shell commands when they contain spaces, wildcard characters, dollar signs, parentheses, brackets, or other characters that the shell could interpret before grep sees them.

Essential grep examples

Search one file

grep 'error' app.log prints every line in app.log containing error. Matching is case-sensitive unless you request otherwise.

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

Show line numbers

grep -n 'error' app.log prefixes each selected line with its line number, which is useful when opening the file in an editor or reporting a defect.

Ignore case

grep -i 'warning' app.log matches warning, Warning, and other case variants.

Search command output

ps aux | grep 'sshd' sends the output of ps aux to grep through a pipe. The same pattern can be used with logs, directory listings, package-manager output, or any command that writes text to standard output.

Include surrounding context

grep -C 2 'failed' app.log prints two lines before and two lines after every matching line. Use -B for only preceding context or -A for only following context.

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.

Search literal text

grep -F 'a.b' file.txt treats the period as an ordinary character. Without -F, the period is a regular-expression metacharacter that can match any single character.

Choose the matching mode

Mode Option Use it when Example
Basic regular expressions (BRE) Default You need regular-expression matching with the traditional grep syntax. grep 'colou?r' file
Extended regular expressions (ERE) -E You want operators such as +, ?, |, and parentheses without the older escaping rules. grep -E 'error|failed' app.log
Fixed strings -F The pattern is exact text and must not be interpreted as a regular expression. grep -F 'a.b' file.txt
Perl-compatible regular expressions -P You specifically need PCRE syntax and your installed GNU grep supports it. grep -P '(?<=ID:)d+' file.txt

-E and -F are specified by POSIX. -P is an implementation-specific GNU option and is not a portable assumption across Unix systems. The exact BRE and ERE details also follow the implementation’s regular-expression rules.

Options that solve common search tasks

  • -i — ignore case distinctions.
  • -n — print input line numbers.
  • -v — invert the match and print lines that do not match.
  • -w — select only whole-word matches where supported.
  • -x — select only lines whose entire content matches.
  • -l — print the names of files with at least one match instead of the matching lines.
  • -L — print names of files with no match.
  • -c — print a count for each file rather than matching lines.
  • -q — quiet mode; stop after determining whether a match exists.
  • -H — include file names in output.
  • -h — suppress file names when several files are searched.
  • -o — print only the matching portions of selected lines where supported.
  • -C N, -B N, -A N — show context around matches.

Options can be combined. For example, grep -Rni --include='*.py' 'TODO' src/ searches Python files below src/, follows all symbolic links, ignores case, and prints line numbers.

Recursive searches

GNU grep: -r versus -R

grep -r 'TODO' src/ recursively searches directories below src/. GNU grep follows symbolic links supplied explicitly on the command line but skips symbolic links encountered while traversing directories. grep -R 'TODO' src/ follows all symbolic links, which can cause a search to leave the apparent tree or revisit files through links.

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

Limit the files you inspect

GNU grep supports filters such as --include='*.js' and --exclude='*.min.js'. These long options are GNU extensions; check your platform’s man grep or info grep before relying on them in portable scripts.

Search hidden or binary content deliberately

Recursive searches may encounter generated, binary, or very large files. Add explicit include/exclude rules, or use the implementation’s binary-file options, when those files would create noise. Do not assume that every grep implementation handles binary data identically.

Patterns, quoting, and regular expressions

Single quotes usually provide the safest shell quoting: grep 'user$' file passes the dollar sign to grep instead of allowing the shell to expand it. Double quotes still allow shell substitutions such as $HOME and command substitution.

Shell filename globbing and regular-expression syntax are different mechanisms. In grep '*.log' file, the asterisk is a regex operator, not a shell filename wildcard, because it is inside quotes; it means “zero or more of the preceding item.” To search for literal wildcard characters, use -F or escape the metacharacters.

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

For alternatives, ERE is often clearer: grep -E 'timeout|connection refused' app.log. For an exact phrase containing punctuation, prefer grep -F 'connection refused' app.log.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Using grep in shell scripts

GNU grep normally returns status 0 when at least one line is selected, 1 when no line is selected, and 2 when an error occurs. That makes it suitable for conditions:

if grep -q '^enabled=true$' settings.conf; then
  echo 'Feature is enabled'
fi

Do not treat every nonzero status as “no match”: status 2 indicates a problem such as an unreadable file or invalid pattern. GNU’s quiet mode has a documented exception: a found match returns 0 even if an error also occurred.

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

When you need to distinguish all outcomes explicitly:

grep -q 'ready' service.log
case $? in
  0) echo 'found' ;;
  1) echo 'not found' ;;
  2) echo 'grep error' >&2; exit 2 ;;
esac

Portability: GNU, BSD, and POSIX grep

The basic command, BRE matching, and the POSIX -E and -F modes are broadly portable. GNU long options, -P, some binary-file controls, and certain context or filename-filter conveniences are not guaranteed by POSIX.

GNU -r and -R also have defined symlink behavior that may differ from another implementation’s recursive options. If a script must run on Linux, macOS, BSD, and other Unix systems, use the POSIX synopsis where possible and verify extensions with the local manual page. GNU documents both man grep and info grep as local references.

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

Common mistakes and fixes

  • Searching for a literal dot or bracket: use -F, for example grep -F '[INFO]' app.log.
  • Getting no results because of case: add -i or use the exact capitalization.
  • Expecting only the matched word: ordinary grep prints the whole selected line; use -o where your implementation supports it, or a tool designed for field extraction.
  • Accidentally searching filenames through the shell: quote the pattern and remember that shell globs are not grep regexes.
  • Missing files in a recursive search: check permissions, excluded paths, symlink behavior, and whether the files are binary.
  • Breaking a script on status 1: distinguish “no match” (1) from an actual grep error (2).

Where grep fits

Use grep when your output is line-oriented and you need filtering, counting, filenames, or nearby context. Use -F for exact text, BRE or -E for regular expressions, and recursive options for directory trees. For structured data such as JSON or CSV, a parser is usually safer than treating the data as unstructured lines. Grep is free software, and the GNU Project publishes its source and documentation.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.