Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 95 ยท Working with Text

grep and Searching Text

Learn grep on Linux: -i -v -n -c -r -l -o -w -E -F, context lines, patterns and anchors, exit codes, searching code and logs, with runnable examples.

grep is the tool you will use more than almost any other. It reads text, keeps the lines that match a pattern, and throws the rest away. The name comes from an old editor command, g/re/p: "globally search for a regular expression and print". With grep you can find the one error in a ten-thousand-line log, every file in a project that mentions a function name, or the users who have a certain shell.

This lesson teaches the options you will use daily, how patterns work at a basic level, how grep reports success through its exit status, and how it fits into pipelines. The pattern language itself (quantifiers, groups, backreferences) gets its own lesson, Regular Expressions for the Shell. We use GNU grep 3.3, the version on most Linux systems; macOS ships BSD grep, which differs in a few options (noted below).

The basics

The shape of the command is grep [options] PATTERN [files...]. Without files, grep reads standard input, which is how it works in a pipeline. By default the pattern is a basic regular expression, and most ordinary words simply match themselves.

Bash Your first greps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Note that apple also matched pineapple juice: grep finds the pattern anywhere in the line. And -c counts lines, so a line with five matches still counts once.

Options you will use all the time

Option Meaning
-i ignore case
-v invert: show non-matching lines
-n prefix lines with their number
-c print only the count of matching lines
-o print only the matched parts, one per line
-w match whole words only
-x the whole line must match
-l / -L list files that do / do not contain a match
-r / -R search directories recursively
-h / -H never / always print file names
-q quiet: print nothing, just set the exit status
-m N stop after N matching lines
-E extended regular expressions (alternation `
-F fixed strings: no regex, the pattern is literal text
-e give a pattern explicitly (use several for OR; needed if it starts with -)
-f FILE read patterns from a file, one per line
-A N / -B N / -C N N lines of context after / before / around

Options can be combined: grep -rniw word dir is a very common recipe (recursive, numbered, ignore case, whole word).

Bash -o, -w, -x, -E and -F

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The dot trap in the last examples is the single most common grep surprise: . matches any character, so searching for the IP address 10.0.0.1 also finds 10x0y0z1. Use -F (or escape the dot as \.) when you mean the literal text.

Patterns and anchors

Even before the full regex lesson you need five pieces of syntax:

  • ^ anchors the pattern to the start of a line, $ to the end. grep '^#' finds comment lines; grep -v '^$' removes empty lines; grep '^$' finds them.
  • . matches any single character, and .* matches any run of characters (including none).
  • [abc] is a character class (one of a, b or c); [^abc] is its negation; [0-9] is a range.
  • \. or [.] matches an actual dot. Backslash removes the special meaning.
  • \< and \> (GNU) match the start and end of a word; -w is the shortcut.

POSIX classes such as [[:digit:]], [[:alpha:]], [[:space:]] and [[:upper:]] are the portable way to say "a digit" or "a letter" regardless of locale.

Bash Anchors and character classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The pair -v -e '^#' -e '^$' is the standard way to print a configuration file without comments or blank lines, and -e can be repeated for several alternative patterns (a logical OR).

Context: seeing the lines around a match

A matching line often only makes sense with its neighbours, for example a stack trace after an error. -A N shows N lines after, -B N shows N before, and -C N both. When groups of context lines are not adjacent, grep prints a -- separator between them.

Bash Context lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

With -n, a matching line shows 3: and a context line shows 4-. This colon-versus-dash convention appears in file names too (file:3:text versus file-4-text), and tools that parse grep output rely on it.

Searching many files

Give grep several files, a glob, or -r for whole directories. When more than one file is searched, each output line is prefixed with the file name.

Bash Searching a small project

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Key points:

  • -r follows only the directories you name and skips symbolic links it meets while descending; -R follows all of them. Without a file argument, -r searches the current directory.
  • --include='*.c' and --exclude-dir=NAME take globs; quote them so the shell does not expand them (see Wildcards and Globbing).
  • When a file looks binary (it contains NUL bytes), grep prints Binary file data.bin matches instead of the line (you can see it in the recursive results above). -a treats the file as text, -I skips binary files.
  • Output order from -r follows directory order, which is not alphabetical, so we pipe into sort for stable output.

Exit codes: grep as a condition

Every command ends with a number, its exit status. grep uses it to answer a yes/no question:

Status Meaning
0 at least one line matched
1 nothing matched (not an error!)
2 an error occurred (bad pattern, missing file)

That makes grep ideal in if statements. Add -q to suppress the output and stop at the first match.

Bash grep exit status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The "no match = 1" rule has a famous consequence: in a script with set -e (stop on errors), a harmless grep that finds nothing can abort the script. Write grep ... || true when "not found" is acceptable, or test it explicitly in an if. More in Exit Codes, set -e and Error Handling.

Never test a command with if [ $(grep -c x file) ]. The simple and correct form is if grep -q x file. It is shorter, handles missing files cleanly, and stops reading at the first match.

grep in pipelines

grep is a filter: text in, fewer lines out. Because it reads standard input you can put it after almost any command.

Bash grep as a filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notice the last test: -w accepts error and warn as separate words but rejects terror and warning, because they are longer words. Combining -F with -f (fixed strings from a file) is also the fastest way to search for thousands of literal strings.

Common pitfalls

  • Quote your patterns. Characters such as *, $, |, ( and spaces are meaningful to the shell. grep error|warn file runs two commands in a pipeline! Write grep -E 'error|warn' file.
  • grep *.txt expands the glob first (grep receives a.txt b.txt and treats a.txt as the pattern). Use grep PATTERN *.txt.
  • Basic versus extended syntax. In a basic regex, +, ?, |, ( and ) are literal and their backslashed forms are special (\+, \|). -E flips this. When in doubt use -E.
  • A pattern starting with a dash needs -e or --: grep -e '-v' file.
  • Matching counts lines, not occurrences. Use -o with wc -l for occurrences.
  • Color is only for terminals. --color=auto highlights matches on a terminal and is off in pipes. grep --color=always sends escape codes into pipes, which breaks later steps.
  • Large files: LC_ALL=C grep ... is much faster on huge ASCII logs because it skips locale-aware matching.

Beyond grep

egrep and fgrep are old names for grep -E and grep -F; they still work but are deprecated. grep -P uses Perl-compatible expressions (lookahead, \d) where the build supports it, though it is a GNU extension and not portable. For searching source code, ripgrep (rg) is a popular replacement: it searches directories recursively by default, respects .gitignore, skips binary and hidden files, and is very fast. It is shown read-only because it is not installed in our sandbox:

CONSOLE
$ rg TODO               # recursive, ignores files listed in .gitignore
$ rg -i 'todo|fixme' -t c   # only C files
$ rg -n -C2 'open\(' src/

Inside Git repositories git grep is another good option (see Git tutorial for the version control side); it searches tracked files only and is very fast. When you need to change the matching lines rather than just find them, move on to sed; when you need to pick fields out of them, use awk.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does grep -c error app.log print?

    -c counts matching lines. A line containing error three times still counts once. To count occurrences use grep -o error file | wc -l.
  2. 2. A script runs grep -q admin users.txt and the status is 1. What does that mean?

    0 means a match was found, 1 means no match, and 2 means an error such as a missing file or an invalid pattern.
  3. 3. You want to find the literal text 192.168.0.1 and nothing else. Which command is safest?

    In a regex each dot matches any character, so the first command also matches 192x168y0z1. -F treats the pattern as plain text. (-w alone does not turn the dots off.)
  4. 4. Which command prints a config file without comment lines (starting with #) and blank lines?

    Two -e patterns combined with -v remove both kinds of lines. The first command still shows blank lines.
  5. 5. Why is grep error|warn app.log wrong?

    Unquoted, | is a shell pipe. Write grep -E 'error|warn' app.log with quotes so grep receives the alternation.

Summary

  • grep PATTERN files prints matching lines; without files it filters standard input.
  • Daily options: -i, -v, -n, -c, -o, -w, -x, -l, -r, -q, plus -A/-B/-C for context.
  • ^ and $ anchor to line ends; . is a wildcard, so use -F or \. for literal dots; use -E for |, +, ? and groups.
  • Quote patterns, and restrict recursive searches with --include and --exclude-dir.
  • Exit status: 0 matched, 1 no match, 2 error. Use grep -q in if and beware set -e.
  • For large trees use LC_ALL=C grep, or the faster ripgrep (rg) on machines where it is installed.

Next: Regular Expressions for the Shell