grep is the standard command-line utility that searches text line by line for a pattern and prints every line that matches. In Linux and other Unix-like systems, it is one of the most frequently used tools in the shell and terminal, reading files named on the command line or standard input from a pipe, which makes it a natural filter in larger command chains.
The name comes from the old ed editor command g/re/p, meaning globally search for a regular expression and print. That origin explains its core idea: grep does not edit or transform text, it selects lines. Editing belongs to sed and field processing to awk, while grep answers the simpler question of where a pattern occurs.
How grep matches lines
grep reads its input one line at a time, tests each line against a compiled pattern and writes the matching lines to standard output. Lines are split on the newline character, so a pattern normally cannot span two lines. The exit status reports the result: 0 when at least one line matched, 1 when nothing matched and 2 when an error occurred, which lets shell scripts branch on a search without parsing its output.
Patterns are regular expressions by default. GNU grep compiles them into an efficient automaton and uses fast string search algorithms for literal fragments, which is why it can scan gigabytes of logs in seconds on ordinary hardware. When several files are given, each matching line is prefixed with its file name unless the -h option suppresses it.
The table below summarizes the three main pattern syntaxes that grep supports and how they differ.
| Mode | Option | Typical behavior |
|---|---|---|
| Basic regular expressions | Default or -G | +, ?, | and braces need a backslash |
| Extended regular expressions | -E (formerly egrep) | Metacharacters work without backslashes |
| Fixed strings | -F (formerly fgrep) | Pattern is matched as plain text, fastest option |
| Perl-compatible expressions | -P (GNU only) | Lookarounds, \d and lazy quantifiers |
Essential grep options
Most practical work with grep relies on a small set of options that control case, context, output format and which files are searched. These flags are defined by the POSIX standard in their basic form, and GNU grep, the version shipped with nearly every Linux distribution, adds many extensions such as recursive search and colored output.
| Option | Effect | Common use |
|---|---|---|
-i | Ignores letter case | Finding error, Error and ERROR together |
-v | Inverts the match | Removing comment or blank lines |
-r / -R | Searches directories recursively | Locating a string across a source tree |
-n | Prints line numbers | Jumping to a match in an editor |
-c | Counts matching lines | Quick frequency checks in logs |
-l | Lists only file names | Feeding files to another command |
-w / -x | Matches whole words or whole lines | Avoiding partial matches |
-A, -B, -C | Adds context lines after, before or around | Reading the surroundings of an error |
-o | Prints only the matched part | Extracting addresses or IDs |
-q | Prints nothing, sets exit status | Conditions in shell scripts |
Options can be combined, for example grep -rni 'timeout' /etc performs a recursive, case-insensitive search with line numbers. The --include and --exclude options restrict recursive searches to specific file name patterns, which keeps results relevant in large directories.
grep in pipelines and scripts
grep is designed as a filter in a pipe: any command that writes text can send it through grep to keep only the interesting lines. A command such as ps aux | grep nginx narrows a long process list, and journalctl -u ssh | grep 'Failed password' isolates failed login attempts from a service log.
In shell scripts, the quiet mode `-q` combined with the exit status turns grep into a test. A line such as if grep -q '^backup:' /etc/passwd; then ... fi checks whether a user exists without printing anything. Because grep stops reading at the first match in quiet mode, such tests are also fast on large files.
For safe handling of unusual file names, grep -lZ outputs null-terminated names that can be passed to xargs -0. This avoids breaking file names that contain spaces or newlines, a classic source of bugs in automation.
How grep compares with sed, awk and ripgrep
grep is one member of a family of text tools, and choosing the right one depends on whether the task is selecting, transforming or computing. The comparison below shows where each tool fits in typical Linux work.
| Tool | Primary purpose | Best suited for |
|---|---|---|
| grep | Selects matching lines | Searching logs, code and configuration |
| sed | Edits a stream of text | Substitutions and line deletions |
| awk | Processes fields and records | Column extraction, sums and reports |
| ripgrep (rg) | Fast recursive code search | Large repositories, respects .gitignore |
| find | Selects files by attributes | Names, sizes, dates and permissions |
A common confusion is between grep and find: find locates files by metadata, while grep searches inside file contents. The two are often combined, for example find . -name '*.conf' -exec grep -H 'Listen' {} +, which searches only configuration files for a directive.
Common grep mistakes and their fixes
Most problems with grep come from shell quoting, regular expression syntax or character encoding, not from the tool itself. The following table lists the symptoms experienced administrators see most often.
| Symptom | Cause | Fix |
|---|---|---|
Pattern with * behaves oddly | Unquoted pattern expanded by the shell | Wrap the pattern in single quotes |
a|b finds nothing | Alternation needs extended syntax | Use grep -E 'a|b' |
| A dot matches any character | . is a metacharacter | Escape it or use -F |
| Binary file matches message | Input contains null bytes | Use -a or --binary-files=text |
ps | grep name lists grep itself | grep process matches its own pattern | Use pgrep or grep '[n]ame' |
| Searches are slow on Unicode text | Multibyte locale processing | Set LC_ALL=C for byte-level search |
Another frequent misunderstanding concerns greedy matching with `-o`: a pattern such as ".*" matches from the first to the last quote on a line. A negated character class such as "[^"]*" limits each match to one quoted string and gives the intended result.
Explained without jargon
grep works like the find function in a word processor, but for the command line and for many files at once. You tell it what word or pattern to look for, and it shows you every line that contains it, leaving out everything else.
Imagine a thick printed logbook where you need every entry that mentions a particular machine. Instead of reading all pages, you hand the book to an assistant who copies out only the matching lines. That is what grep does with text, in a fraction of a second, and it can also tell you how many lines matched or which files contained them.
A typical use case
A system administrator receives a report that a web application returned errors for about twenty minutes in the early morning. The server writes roughly 2 GB of access logs per day, far too much to read manually. The administrator runs grep -c ' 50[0-9] ' access.log to count server error responses and finds about 4,800 of them, compared with a usual daily figure of a few dozen.
Next, grep ' 50[0-9] ' access.log | grep -o '/api/[a-z]*' | sort | uniq -c | sort -rn shows that almost all errors hit a single endpoint, and grep -B 3 -A 10 'Traceback' app.log reveals a database connection timeout behind them. Within about fifteen minutes, the cause is identified: a scheduled database backup was locking a table. The backup is moved to a quieter hour, and the same grep commands become a monitoring check that alerts the team if the error count rises again.