---
title: "Grep"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/grep
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Grep

Complete grep reference with pattern matching, regular expressions, flags, context options, and practical examples for searching text files

7 Categories24 Sections48 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

GrepSearchPattern MatchingRegular ExpressionsRegexLinux

[Markdown for AI(opens in a new tab)](/grep/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Linux & System Administration](/series/linux--system-administration)7/12

[PreviousFind](/cheatsheets/find)[NextNetcat](/cheatsheets/nc)

All posts in this series (12)

Cheatsheets12

1.  [AWK](/cheatsheets/awk)
2.  [Bash](/cheatsheets/bash)
3.  [Chmod](/cheatsheets/chmod)
4.  [Cron](/cheatsheets/cron)
5.  [Curl](/cheatsheets/curl)
6.  [Find](/cheatsheets/find)
7.  [GrepYou are here](/cheatsheets/grep)
8.  [Netcat](/cheatsheets/nc)
9.  [Netstat](/cheatsheets/netstat)
10.  [Sed](/cheatsheets/sed)
11.  [SSH](/cheatsheets/ssh)
12.  [Linux Networking](/cheatsheets/linux-networking)

## [Best practices for grep usage](#best-practices-for-grep-usage)

-   **Always quote patterns** to prevent shell interpretation of special characters
-   **Use -E flag for complex patterns** to avoid escaping issues with basic regex
-   **Test patterns on sample data** before running on production systems
-   **Use -n with debugging** to quickly navigate to errors in code
-   **Combine with pipes** to build data processing pipelines
-   **Use -F for literal strings** when you don’t need regex (much faster)
-   **Use -w for word boundaries** to avoid partial word matches in code
-   **Use anchors** (^ for start, $ for end) to match precise patterns
-   **Exclude directories early** with grep -r to improve performance
-   **Use —color=always in pipes** to highlight matches in complex pipelines

## [Common errors and solutions](#common-errors-and-solutions)

-   **error: “No such file or directory”** → Check file path exists and permissions are correct
-   **error: “grep: (standard input): No such device”** → Check input method; the piped input may not be valid
-   **error: “Invalid regular expression”** → Check regex syntax; escape special characters or use -F for literals
-   **error: “Binary file matches”** → Use -a flag or —binary-files=text to treat as text
-   **error: “Nothing found when expecting matches”** → Verify pattern is correct; test pattern syntax with sample data
-   **error: “Searching too slowly”** → Use -F for literals, limit results with -m, exclude directories with —exclude-dir

* * *

ref: [https://man7.org/linux/man-pages/man1/grep.1.html](https://man7.org/linux/man-pages/man1/grep.1.html)

[Getting Started](#category-getting-started)

-   [What is Grep](#section-what-is-grep)
-   [Installation and Setup](#section-installation-setup)

[Basic Pattern Matching](#category-basic-pattern-matching)

-   [Simple Text Search](#section-simple-text-search)
-   [Case-Insensitive Search](#section-case-insensitive-search)
-   [Whole Word Matching](#section-whole-word-matching)
-   [Whole Line Matching](#section-whole-line-matching)
-   [Multiple Patterns](#section-multiple-patterns)

[Regular Expressions](#category-regular-expressions)

-   [Basic Regular Expressions](#section-basic-regex-patterns)
-   [Extended Regular Expressions](#section-extended-regex)
-   [Anchors and Boundaries](#section-anchors-and-boundaries)
-   [Repetition Operators](#section-repetition-operators)

[Output Control](#category-output-control)

-   [Count Matches and Suppress Output](#section-count-and-suppress)
-   [Line Numbers and File Names](#section-line-numbers-and-files)
-   [Show Only Matched Text](#section-matched-text-output)
-   [Color Output and Byte Offsets](#section-color-and-offsets)

[Context and Line Selection](#category-context-and-lines)

-   [Context Lines Around Matches](#section-context-lines)
-   [Invert Match](#section-invert-match)
-   [Max Count and File Listing](#section-max-count-and-files)

[File and Directory Operations](#category-file-operations)

-   [Recursive Directory Search](#section-recursive-search)
-   [File and Directory Exclusion](#section-file-exclusion)
-   [Binary Files and Special Input](#section-special-options)

[Practical Examples and Advanced Usage](#category-advanced-usage)

-   [Real-World Use Cases](#section-practical-examples)
-   [Advanced Regular Expression Patterns](#section-advanced-patterns)
-   [Performance Optimization](#section-performance-tips)

No commands found

Try adjusting your search term

## Getting Started

Introduction to grep and basic concepts

### What is Grep

Grep and its use cases for text searching

#### Accessibility

Clear introduction to grep concepts and capabilities

#### Best Practices

-   Use single quotes to protect patterns from shell interpretation
-   Test patterns on small files before running on large datasets
-   Use -E for consistent extended regex syntax
-   Combine multiple flags in one invocation

#### Common Errors

-   **No such file or directory:** Verify file path exists and check spelling

#### Keywords

grepsearchpatterntextfiles

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Grep overview and basic usage

Grep searches for lines containing the pattern "ap" regardless of position in the line.

Code

Terminal window

```
# Grep stands for: global regular expression print# It searches for lines matching a pattern in files
# Basic syntax: grep [OPTIONS] PATTERN [FILE...]# Prints lines that match the pattern
# Key features:# - Search multiple files# - Use regular expressions for powerful patterns# - Filter and display specific lines# - Count matches# - Case-insensitive search# - Show context around matches
```

Execution

Terminal window

```
echo -e "apple\nbanana\ncherry\napricot" | grep "ap"
```

Output

Terminal window

```
appleapricot
```

-   Grep is case-sensitive by default
-   Pattern can be literal text or regular expression
-   Matches any line containing the pattern (substring match)
-   Returns nothing if no matches found

#### Grep vs other text processing tools

Grep handles simple pattern matching and filtering. The ^ anchor matches line start, so only error lines pass.

Code

Terminal window

```
# Compare grep with similar tools:# grep: Search for patterns in lines (filtering)# sed: Stream editor for text transformations# awk: Full text processing language with patterns# find: Search for files by name or properties
# Use grep when you need:# - Quick pattern matching in text# - Filter lines based on conditions# - Search in multiple files# - Use regular expressions for search
```

Execution

Terminal window

```
echo -e "error: connection failed\ninfo: starting\nerror: timeout" | grep "^error"
```

Output

Terminal window

```
error: connection failederror: timeout
```

-   Grep is best for pattern filtering tasks
-   Faster than awk for simple searches
-   Easier than sed for match-based filtering
-   Can pipe to other commands for complex workflows

### Installation and Setup

Installing grep and verifying functionality

#### Accessibility

Clear installation steps for different systems

#### Best Practices

-   Use system package manager to install grep
-   On macOS, consider installing GNU grep for compatibility
-   Verify installation with --version flag

#### Common Errors

-   **grep: command not found:** Install grep using package manager or check PATH

#### Keywords

installsetupversiongrepDependencies

[Learn more](https://linux.die.net/man/1/grep)

#### Verify grep installation

Grep is typically pre-installed on Linux and Unix systems. Display version and confirm functionality.

Code

Terminal window

```
# Check if grep is installedwhich grep
# Display grep versiongrep --version
# Show grep helpgrep --help | head -20
```

Execution

Terminal window

```
grep --version
```

Output

Terminal window

```
grep (GNU grep) 3.7Copyright (C) 2021 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later.
```

-   Grep is usually included by default on Linux systems
-   Different implementations: GNU grep, BSD grep
-   GNU grep is typically more feature-rich
-   Version may vary across systems

#### Install grep on different systems

Installation of grep across different Linux distributions and macOS systems.

Code

Terminal window

```
# Ubuntu/Debiansudo apt-get updatesudo apt-get install -y grep
# CentOS/RHELsudo yum install -y grep
# macOS (BSD grep is default)brew install grep  # Installs GNU grep as ggrep
# Alpine Linuxapk add grep
# Arch Linuxsudo pacman -S grep
```

Execution

Terminal window

```
which grep && grep --version | head -1
```

Output

Terminal window

```
/usr/bin/grepgrep (GNU grep) 3.7
```

-   GNU grep is the most feature-complete version
-   macOS comes with BSD grep; install GNU grep with Homebrew
-   Always available on standard Linux deployments
-   Some advanced flags may not work on BSD grep

## Basic Pattern Matching

Simple text search and basic pattern techniques

### Simple Text Search

Basic pattern matching for literal text

#### Accessibility

Clear examples of simple text searching

#### Best Practices

-   Quote patterns to prevent shell interpretation
-   Use grep as a filter in pipelines
-   Test with small amounts of data first

#### Common Errors

-   **grep: command not found:** Grep not in PATH; install or add to PATH

#### Keywords

searchpatternliteraltextbasic

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Search for literal text in files

Grep searches for any line containing the pattern "hello" anywhere in the line.

Code

Terminal window

```
# Search for a pattern in a filegrep "pattern" filename
# Search in multiple filesgrep "pattern" file1 file2 file3
# Search with different patternsgrep "hello" sample.txtgrep "error" log.txtgrep "TODO" code.py
```

Execution

Terminal window

```
echo -e "function test() {\n  console.log('hello')\n}\ntest('world')" | grep "hello"
```

Output

Terminal window

```
console.log('hello')
```

-   Grep is case-sensitive by default
-   Pattern is a substring match (anywhere in line)
-   Returns full line containing match, not just the matched text
-   Returns nothing if no matches found

#### Read from standard input

Grep processes standard input when no file is specified, useful in pipelines.

Code

Terminal window

```
# Pipe command output to grepcat file.txt | grep "pattern"
# Use echo to create inputecho "test string" | grep "test"
# Chain multiple commandscat log.txt | grep "error" | grep "database"
```

Execution

Terminal window

```
echo -e "line1\nerror: failed\nline3\nerror: retry" | grep "error"
```

Output

Terminal window

```
error: failederror: retry
```

-   Use pipe | to send data to grep
-   Grep waits for input from stdin if no file given
-   Useful in command pipelines for filtering
-   Can filter output from other commands

### Case-Insensitive Search

Matching patterns regardless of letter case

#### Accessibility

Examples of case-insensitive pattern matching

#### Best Practices

-   Use -i for log file searching where case varies
-   Combine with -n to show line numbers
-   Use in pipes to filter case-insensitive results

#### Common Errors

-   **No output when expecting matches:** Check if -i flag is used for case variations

#### Keywords

caseinsensitiveflagignorecase-i

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Case-insensitive search with -i flag

The -i flag makes grep ignore case differences, matching all variations of the pattern.

Code

Terminal window

```
# Search ignoring case with -i flaggrep -i "pattern" filename
# Works for any case combinationgrep -i "ERROR" file.txt    # matches: error, Error, ERRORgrep -i "hello" text.txt    # matches: hello, Hello, HELLO
```

Execution

Terminal window

```
echo -e "Hello World\nhello world\nHELLO WORLD" | grep -i "hello"
```

Output

Terminal window

```
Hello Worldhello worldHELLO WORLD
```

-   \-i stands for --ignore-case
-   Matches regardless of uppercase/lowercase
-   Useful for log files with inconsistent capitalization
-   Works with literal text and regular expressions

#### Case-insensitive search in multiple files

Case-insensitive search matches every capitalisation of the pattern.

Code

Terminal window

```
# Search multiple files ignoring casegrep -i "Warning" *.log
# Combine with line numbersgrep -in "ERROR" error.loggrep -in "info" system.log
```

Execution

Terminal window

```
echo -e "WARNING: disk full\nWarning: memory\nwARNING: cpu" | grep -i "warning"
```

Output

Terminal window

```
WARNING: disk fullWarning: memorywARNING: cpu
```

-   Useful for searching logs with variable capitalization
-   Can combine -i with other flags like -n or -c
-   Works in pipelines

### Whole Word Matching

Match complete words without partial matches

#### Accessibility

Examples of word boundary matching

#### Best Practices

-   Use -w when searching for specific keywords in code
-   Combine -w with -i for flexible matching
-   Use -w to avoid partial word matches in data

#### Common Errors

-   **Losing expected matches with word boundaries:** Verify word boundaries with -w; some punctuation may affect matching

#### Keywords

wordboundarywhole\-wcomplete

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Match whole words with -w flag

The -w flag matches only "cat" as a complete word, excluding "concatenate" which contains "cat" as part of a larger word.

Code

Terminal window

```
# -w flag matches only complete wordsgrep -w "word" filename
# Avoids partial matches# "word" matches: word, the word is# "word" does NOT match: sword, wording, foreword
grep -w "cat" pets.txt   # only standalone "cat"grep -w "test" code.py   # only "test" word, not in "testing"
```

Execution

Terminal window

```
echo -e "the cat sat\nconcatenate strings\ncat is here" | grep -w "cat"
```

Output

Terminal window

```
the cat satcat is here
```

-   \-w stands for --word-regexp
-   Matches word boundaries (space, punctuation, start/end)
-   Useful for searching code to avoid partial matches
-   Works with regular expressions too

#### Whole word search ignoring case

Combining -i and -w provides case-insensitive whole word matching.

Code

Terminal window

```
# Combine -w with -i for case-insensitive word matchinggrep -iw "The" text.txt
# Searches for complete words ignoring casegrep -iw "error" log.txt    # matches: error, Error, ERRORgrep -iw "function" code.js # matches complete word "function"
```

Execution

Terminal window

```
echo -e "The quick brown fox\nthe lazy dog\nThey will go" | grep -iw "the"
```

Output

Terminal window

```
The quick brown foxthe lazy dog
```

-   \-iw combines ignore-case and word-regexp
-   More flexible searching for code and logs
-   Avoids false positives from partial matches

### Whole Line Matching

Match patterns that span entire lines

#### Accessibility

Examples of exact line matching

#### Best Practices

-   Use -x for exact line matching in configuration files
-   Combine -x with -E for precise pattern validation
-   Use -x to avoid partial line matches

#### Common Errors

-   **Pattern does not match when appearing in line:** -x requires exact line match; use partial pattern match without -x

#### Keywords

lineexactwhole\-xanchors

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Match exact lines with -x flag

The -x flag only matches lines containing exactly "test" with nothing else.

Code

Terminal window

```
# -x flag matches entire line onlygrep -x "exact line" filename
# Pattern must match complete line (not substring)# "test" matches: test (exact match)# "test" does NOT match: test123, mytest, testing
grep -x "TRUE" config.txtgrep -x "done" status.log
```

Execution

Terminal window

```
echo -e "test\ntest123\nmy test\nonlytest" | grep -x "test"
```

Output

Terminal window

```
test
```

-   \-x stands for --line-regexp
-   Useful for matching configuration file values
-   Equivalent to anchoring pattern with ^...$
-   Strict matching without partial line matches

#### Exact line matching with regex patterns

\-x requires the pattern to match the complete line. The pattern matches exactly 3 digits.

Code

Terminal window

```
# Use -x with regex for exact line patternsgrep -x "status:.*" config.txt
# Match specific line formatgrep -x "[0-9]\{3\}" numbers.txt  # exactly 3 digitsgrep -xE "^[a-z]+$" words.txt    # lowercase letters only
```

Execution

Terminal window

```
echo -e "123\n12\n1234\n12a" | grep -x "[0-9][0-9][0-9]"
```

Output

Terminal window

```
123
```

-   \-x requires complete line match including spaces
-   Combine with -E for extended regex
-   Useful for structured data validation

### Multiple Patterns

Search for multiple patterns using different methods

#### Accessibility

Examples of matching multiple patterns

#### Best Practices

-   Use -E with | for cleaner multiple pattern syntax
-   Use multiple -e for simple literal patterns
-   Combine with -i for case-insensitive matching

#### Common Errors

-   **Patterns not matching as expected:** Escape special regex characters or use -F for literal text

#### Keywords

multiplepatterns\-eoralternation

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Match multiple patterns with -e flag

The -e flag allows matching multiple patterns. Lines matching any pattern are included.

Code

Terminal window

```
# Use -e for each pattern (OR logic)grep -e "pattern1" -e "pattern2" filename
# Matches lines with pattern1 OR pattern2grep -e "error" -e "warning" log.txtgrep -e "TODO" -e "FIXME" code.py
# Can use multiple -e flagsgrep -e "info" -e "debug" -e "error" app.log
```

Execution

Terminal window

```
echo -e "error: failed\nwarning: deprecated\ninfo: started\nerror: retry" | grep -e "error" -e "warning"
```

Output

Terminal window

```
error: failedwarning: deprecatederror: retry
```

-   Each -e adds another pattern to match (OR logic)
-   Returns lines matching any pattern
-   Useful for filtering multiple categories
-   Can combine with other flags like -i or -c

#### Alternation with extended regex

The -E flag enables extended regex with | for alternation, matching any alternative.

Code

Terminal window

```
# Use pipe | for alternation with -E flaggrep -E "pattern1|pattern2" filename
# Single pattern but with alternativesgrep -E "error|warning" log.txtgrep -E "\.js|\.ts" files.txt
# More complex patternsgrep -E "(fruit|vegetable)" grocery.txt
```

Execution

Terminal window

```
echo -e "apple fruit\nbroccoli vegetable\nstrawberry fruit\ncarrot vegetable" | grep -E "fruit|vegetable"
```

Output

Terminal window

```
apple fruitbroccoli vegetablestrawberry fruitcarrot vegetable
```

-   \-E enables extended regular expressions
-   Pipe | provides cleaner syntax for multiple patterns
-   Works with groups: (pattern1|pattern2)
-   More flexible than multiple -e flags

## Regular Expressions

Advanced pattern matching using regular expressions

### Basic Regular Expressions

Basic regex patterns and syntax

#### Accessibility

Introduction to regex patterns in grep

#### Best Practices

-   Use character classes for flexible pattern matching
-   Anchor patterns with ^ and $ for precise matches
-   Test complex patterns on sample data first

#### Common Errors

-   **Extended regex needs flag:** Use -E flag for extended regex with +, ?, |

#### Keywords

regexregularexpressionpatternbasic

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#Basic-vs-Extended)

#### Basic regex metacharacters

The ^ anchor matches only lines starting with "error". The $ would match lines ending with a pattern.

Code

Terminal window

```
# Basic regex characters (BRE - Basic Regular Expressions)# . = any character# * = zero or more of previous# ^ = start of line# $ = end of line# [abc] = any of a, b, c# [^abc] = not a, b, or c
grep "^error" log.txt       # lines starting with errorgrep "\.py$" files.txt      # lines ending with .pygrep "^[0-9]" data.txt      # lines starting with digit
```

Execution

Terminal window

```
echo -e "error: failed\nwarning: check\nerror: retry\ninfo: started" | grep "^error"
```

Output

Terminal window

```
error: failederror: retry
```

-   Grep uses Basic Regular Expressions (BRE) by default
-   In BRE, some characters need backslash escaping
-   ^ and $ are line anchors, not in pattern
-   . matches any single character except newline

#### Character classes and ranges

The pattern "test\[0-9\]" matches "test" followed by any single digit.

Code

Terminal window

```
# Character classes [] match any character in the setgrep "[0-9]" file.txt         # any digitgrep "[a-z]" file.txt         # any lowercase lettergrep "[A-Z]" file.txt         # any uppercase lettergrep "[a-zA-Z]" file.txt      # any lettergrep "[^0-9]" file.txt        # NOT a digit
# Common patternsgrep "[aeiou]" words.txt      # contains vowelgrep "test[0-9]" results.txt  # test followed by digit
```

Execution

Terminal window

```
echo -e "test1\ntest2a\nrandom\ntest" | grep "test[0-9]"
```

Output

Terminal window

```
test1test2a
```

-   \[0-9\] is equivalent to \\d in other regex flavors
-   \[^...\] negates the character class
-   Ranges use hyphen: \[a-z\] for lowercase letters
-   Order doesn't matter in character class

### Extended Regular Expressions

Extended regex syntax with the -E flag

#### Accessibility

Extended regex pattern examples

#### Best Practices

-   Use -E for cleaner pattern syntax
-   Always quote patterns to prevent shell interpretation
-   Test patterns with known inputs first

#### Common Errors

-   **Invalid regular expression:** Check syntax; use -F for literal text if pattern appears invalid

#### Keywords

extendedregex\-EEREflag

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#Basic-vs-Extended)

#### Extended regex patterns with -E

The -E flag enables extended regex. The + means one or more, matching test followed by one or more digits.

Code

Terminal window

```
# Extended Regular Expressions (ERE) with -E flag# + = one or more# ? = zero or one# () = grouping# | = alternation# {} = repetition count
grep -E "error+" log.txt         # error, errorr, errorrrgrep -E "test[0-9]+" file.txt   # test followed by 1+ digitsgrep -E "colou?r" text.txt      # color or colourgrep -E "(cat|dog)" pets.txt    # cat or dog
```

Execution

Terminal window

```
echo -e "test\ntest1\ntest123\ntest1a" | grep -E "test[0-9]+"
```

Output

Terminal window

```
test1test123test1a
```

-   \-E flag enables extended regex (ERE)
-   Cleaner syntax than BRE with + ? {n,m}
-   More intuitive than escaping in BRE
-   Recommended for complex patterns

#### Complex extended regex patterns

The pattern validates an exact format of three digits, hyphen, two digits, hyphen, four digits, held in place by the ^ and $ anchors.

Code

Terminal window

```
# Complex patterns with extended regexgrep -E "^[0-9]{3}-[0-9]{2}-[0-9]{4}$" ssn.txtgrep -E "^[a-z]+@[a-z]+\.[a-z]+$" emails.txtgrep -E "^https?://" urls.txtgrep -E "^(admin|root):" /etc/passwd
# Combinations with modifiersgrep -E "(test|demo)_[0-9]{2,4}" files.txt
```

Execution

Terminal window

```
echo -e "123-45-6789\n12-45-6789\nabc-45-6789" | grep -E "^[0-9]{3}-[0-9]{2}-[0-9]{4}$"
```

Output

Terminal window

```
123-45-6789
```

-   {n,m} matches between n and m occurrences
-   {n} matches exactly n occurrences
-   Anchors ^ and $ force an exact match
-   Parentheses group patterns for | alternation

### Anchors and Boundaries

Line and word boundary patterns

#### Accessibility

Examples of anchor patterns

#### Best Practices

-   Use ^ to match lines starting with pattern
-   Use $ to match lines ending with pattern
-   Use -w instead of \\b for simpler word matching
-   Combine anchors for precise matching

#### Common Errors

-   **Matches not starting at beginning:** Add ^ anchor to force start-of-line matching

#### Keywords

anchorboundarystartend^$\\b

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#The-Backslash-Operator)

#### Line anchors for position matching

The $ anchor matches "error" only at the end of the line, not in the middle.

Code

Terminal window

```
# ^ = start of line# $ = end of line
grep "^error" log.txt        # lines starting with errorgrep "\.log$" files.txt      # lines ending with .loggrep "^$" file.txt           # empty linesgrep "^[0-9]" data.txt       # lines starting with digitgrep "success$" results.txt  # lines ending with success
```

Execution

Terminal window

```
echo -e "error: failed\nwarning: error\nerror at end" | grep "error$"
```

Output

Terminal window

```
error at end
```

-   ^ matches position before first character
-   $ matches position after last character
-   ^$ together match entirely empty lines
-   Anchors match position, not actual content

#### Word boundaries in extended regex

Word boundaries \\b match "test" only as a standalone word, not within "marketesting" or "testing".

Code

Terminal window

```
# Word boundary matching (requires -E or -P)grep -E "\\btest\\b" file.txt     # complete wordgrep -E "^[a-z]+$" words.txt      # exactly lowercasegrep -E "\\bserver\\b:" config.txt # word boundary match
# Alternative: use -w flag for word boundariesgrep -w "test" file.txt           # simpler approach
```

Execution

Terminal window

```
echo -e "test word\nmarketesting\ntest: started\ntesting" | grep -E "\\btest\\b"
```

Output

Terminal window

```
test wordtest: started
```

-   \\b matches word boundaries (letter/non-letter transitions)
-   \-w flag provides simpler word boundary matching
-   Anchors ^ and $ prevent partial matches

### Repetition Operators

Matching repeated characters and patterns

#### Accessibility

Examples of repetition patterns

#### Best Practices

-   Use \* for zero or more matches
-   Use + with -E for one or more matches
-   Use {n,m} for precise repetition counts
-   Test repetition patterns on sample data

#### Common Errors

-   **Invalid regular expression:** For {n,m}, use -E flag or escape with \\{ \\}

#### Keywords

repetitionquantifier\*+?{n,m}

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#Basic-vs-Extended)

#### Repetition with asterisk and plus

The + operator requires at least one 'u'. With \*, zero or more would match "color" too.

Code

Terminal window

```
# * = zero or more of previous (BRE default)# + = one or more of previous (requires -E)
grep "error*" log.txt      # error, eror, errror (BRE)grep -E "error+" log.txt   # error, errorr, errror (ERE)grep -E "a+b" file.txt     # a, aa, aaa, ... followed by bgrep -E "0*1" file.txt     # 1, 01, 001, etc
# Practical examplesgrep "^#+$" readme.txt     # lines of only # charactersgrep -E "^-+$" file.txt    # separator lines (dashes)
```

Execution

Terminal window

```
echo -e "color\ncolour\ncolouur\ncolr" | grep -E "colou+r"
```

Output

Terminal window

```
colourcolourr
```

-   \* includes zero occurrences (matches "error" for pattern "error\*")
-   \+ requires at least one (doesn't match "error" for pattern "error+")
-   Use -E for + operator
-   Without -E, need to escape: \\+

#### Counting repetitions with braces

The {2,4} pattern matches 2 to 4 'a' characters, excluding single 'a' and 'aaaa'.

Code

Terminal window

```
# {n} = exactly n times# {n,m} = between n and m times# {n,} = n or more times
grep -E "a{2}" file.txt        # aa, aaa, aaaagrep -E "a{2,4}" file.txt      # aa, aaa, aaaagrep -E "[0-9]{3}" file.txt    # exactly 3 digitsgrep -E "[0-9]{2,}" file.txt   # 2 or more digits
# Real-world examplesgrep -E "[0-9]{3}-[0-9]{3}-[0-9]{4}" phones.txt  # phone regex
```

Execution

Terminal window

```
echo -e "a\naa\naaa\naaaa\naaaaa" | grep -E "a{2,4}"
```

Output

Terminal window

```
aaaaaaaaa
```

-   {n,m} is more precise than \* or +
-   Useful for validation patterns
-   Requires -E flag
-   BRE requires escaping: \\{n,m\\}

## Output Control

Controlling what grep displays

### Count Matches and Suppress Output

Count matching lines and suppress normal output

#### Accessibility

Examples of output control

#### Best Practices

-   Use -c for counting matches in reports
-   Use -q in shell scripts for conditionals
-   \[object Object\]

#### Common Errors

-   **Unexpected output with -c:** -c returns count, not lines; use without -c for lines

#### Keywords

count\-csuppress\-qquiet

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Count matching lines with -c

The -c flag returns count of matching lines (3) instead of printing them.

Code

Terminal window

```
# -c flag counts matching lines instead of printing themgrep -c "pattern" filename
# Shows number of lines matching, not the linesgrep -c "error" log.txt      # outputs: 42grep -c "warning" log.txt    # outputs: 13grep -c "^#" script.sh       # count comment lines
# Combine with other patternsgrep -c "^" file.txt         # total line count
```

Execution

Terminal window

```
echo -e "error\nwarning\nerror\nerror\ninfo" | grep -c "error"
```

Output

Terminal window

```
3
```

-   \-c counts matching lines, not total matches
-   Useful for statistics and reporting
-   Returns 0 if no matches found
-   Faster than counting lines manually

#### Suppress output with -q

The -q flag suppresses output and returns exit code to check if pattern exists.

Code

Terminal window

```
# -q (quiet) suppresses output# Returns exit code: 0 if match found, 1 otherwisegrep -q "pattern" filename
# Useful in scripts for conditional logicif grep -q "error" log.txt; then  echo "Errors found"fi
# Check if word exists in filegrep -q "^root:" /etc/passwd && echo "root user exists"
```

Execution

Terminal window

```
echo -e "apple\nbanana\ncherry" | grep -q "banana" && echo "found"
```

Output

Terminal window

```
found
```

-   \-q returns exit code (0=found, 1=not found)
-   No output produced with -q
-   Useful in conditional statements and scripts
-   Faster than redirecting to /dev/null

### Line Numbers and File Names

Display line numbers and file names in output

#### Accessibility

Examples showing line and file information

#### Best Practices

-   Always use -n when debugging code/log issues
-   Use -H explicitly when searching multiple files
-   Combine -Hn for best navigation information

#### Common Errors

-   **No file names shown:** Use -H flag explicitly for multiple files

#### Keywords

linenumber\-nfile\-H\-h

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Display line numbers with -n

The -n flag shows line numbers (2 and 4) before each matching line.

Code

Terminal window

```
# -n flag displays line numbers before each matchgrep -n "pattern" filename
# Shows line number and matched linegrep -n "error" log.txtgrep -n "TODO" code.pygrep -n "(function|method)" *.js
# Useful with head/tail for contextgrep -n "pattern" file.txt | head -5
```

Execution

Terminal window

```
echo -e "line1\nerror: failed\nline3\nerror: retry\nline5" | grep -n "error"
```

Output

Terminal window

```
2:error: failed4:error: retry
```

-   Line numbers are 1-based (first line is 1)
-   Useful for locating errors in code/logs
-   Can navigate directly to line with editor :N syntax
-   Combine with pipes for further filtering

#### Show file names with -H and -h

The -H flag shows filename with each match when searching multiple files.

Code

Terminal window

```
# -H flag shows filename for each matchgrep -H "pattern" *.txt
# -h flag suppresses filename (default for single file)grep -h "pattern" file1.txt file2.txt
# Combine -H with line numbersgrep -Hn "ERROR" *.log
# Useful with multiple file searchesgrep -r -H "pattern" directory/
```

Execution

Terminal window

```
echo "error message" > /tmp/test1.txt && echo "error found" > /tmp/test2.txt && grep -H "error" /tmp/test*.txt
```

Output

Terminal window

```
/tmp/test1.txt:error message/tmp/test2.txt:error found
```

-   \-H shows filename (useful for multiple files)
-   \-h suppresses filename (useful to avoid duplicates)
-   Default behavior varies by grep implementation
-   Combine -H and -n: grep -Hn pattern file produces file:line:text

### Show Only Matched Text

Display only the matched portion of lines

#### Accessibility

Examples of matched text extraction

#### Best Practices

-   Use -o for extracting specific patterns
-   Combine -o with pipes for data processing
-   Use -oE for complex pattern extraction

#### Common Errors

-   **No matches displayed:** Verify pattern exactly matches; test with -E if using complex regex

#### Keywords

matchedtext\-ooutputonly

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Show only matched part with -o

The -o flag shows only matched patterns, not full lines.

Code

Terminal window

```
# -o flag shows only the matched text, not full linesgrep -o "pattern" filename
# Useful for extracting specific patternsgrep -o "[0-9]*\.[0-9]*" file.txt    # numbers with decimalsgrep -o "[a-z]*@[a-z]*" emails.txt   # email addressesgrep -oE "https?://[^ ]+" urls.txt   # URLs
# Count matches (not lines) with -o and -cgrep -o "word" file.txt | wc -l
```

Execution

Terminal window

```
echo "error: 123 warning: 456 error: 789" | grep -o "error: [0-9]*"
```

Output

Terminal window

```
error: 123error: 789
```

-   \-o shows only matched text, not full line
-   Useful for extracting data (numbers, emails, URLs)
-   Can pipe to other commands for further processing
-   One match per line in output

#### Extract patterns with -o and regex

The -o flag with -E extracts phone numbers matching the pattern.

Code

Terminal window

```
# Extract specific data from structured textgrep -oE "[0-9]{3}-[0-9]{3}-[0-9]{4}" data.txt   # phone numbersgrep -oE "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}" file.txt  # emailsgrep -oE "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" log.txt  # IPs
# Count specific matchesgrep -o "abc" myfile.txt | wc -l       # count "abc" occurrences
```

Execution

Terminal window

```
echo "Call: 555-123-4567 or 555-987-6543" | grep -oE "[0-9]{3}-[0-9]{3}-[0-9]{4}"
```

Output

Terminal window

```
555-123-4567555-987-6543
```

-   Used for data extraction from text
-   Combine with pipes for processing: grep -o "pattern" | sort | uniq
-   Works well with extended regex (-E)

### Color Output and Byte Offsets

Highlight matches and show byte positions

#### Accessibility

Examples of styled output

#### Best Practices

-   Use --color=always in pipes for better visibility
-   Use -b when precise byte positions are needed
-   Combine --color with other flags for clarity

#### Common Errors

-   **No color in output:** Use --color=always flag explicitly

#### Keywords

colorhighlight\-boffsetbytes

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Color output with highlight

The --color flag highlights matching text, useful for visual inspection.

Code

Terminal window

```
# --color flag highlights matches with colorgrep --color "pattern" filename
# Force color output (useful in pipes)grep --color=always "error" log.txt | less -R
# Disable color outputgrep --color=never "pattern" file.txt
# Color in pipelines (useful for inspection)cat log.txt | grep --color=always "error"
```

Execution

Terminal window

```
echo "error in line\nno match here\nerror again" | grep --color=always "error"
```

Output

Terminal window

```
error in lineerror again
```

-   \--color highlights the matched portion
-   Default is automatic color detection
-   Use --color=always in pipes to force coloring
-   Use --color=never to suppress coloring

#### Show byte offset with -b

The -b flag shows byte offset (10) where "def" begins in that line.

Code

Terminal window

```
# -b flag shows byte offset of matchesgrep -b "pattern" filename
# Shows position from start of line where match beginsgrep -b "error" log.txtgrep -bn "pattern" file.txt    # with line numbers
# Useful for binary file analysisgrep -b "signature" binary_file | head
```

Execution

Terminal window

```
echo -e "123456789\nabcdefghij\n0123456789" | grep -b "def"
```

Output

Terminal window

```
10:abcdefghij
```

-   \-b shows byte position from start of line
-   Useful for binary files and precise positioning
-   Can combine with -n for line and byte info
-   Less common flag but useful for specialized tasks

## Context and Line Selection

Display context around matches and filter lines

### Context Lines Around Matches

Show lines before and after matches

#### Accessibility

Examples of context display

#### Best Practices

-   Use -C 2 or -C 3 for general context viewing
-   Combine with -n for location information
-   Use in pipes on large log files for navigation

#### Common Errors

-   **Too much output:** Reduce context numbers (-C 1 instead of -C 5)

#### Keywords

context\-Bbefore\-Aafter\-C

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Show context with -B, -A, and -C

The -A 2 flag shows the matching line plus 2 lines after it.

Code

Terminal window

```
# -B NUM = lines before match# -A NUM = lines after match# -C NUM = lines before and after match
grep -B 2 "error" log.txt        # 2 lines beforegrep -A 3 "ERROR" log.txt        # 3 lines aftergrep -C 1 "pattern" file.txt     # 1 line before and after
# Useful for understanding contextgrep -B 5 -A 5 "Search term" document.txtgrep -C 2 "Connection refused" system.log
```

Execution

Terminal window

```
echo -e "start\nline2\nerror\nline4\nline5" | grep -A 2 "error"
```

Output

Terminal window

```
errorline4line5
```

-   \-A adds lines after the match
-   \-B adds lines before the match
-   \-C adds both before and after
-   NUM is the number of lines to display

#### Context with line numbers and colors

Multiple context groups are separated by dashes. Each match shows surrounding lines.

Code

Terminal window

```
# Combine context with other useful flagsgrep -C 3 -n "pattern" file.txt      # context + line numbersgrep -C 2 --color "error" log.txt    # context + color
# Separate output with dashes (useful for multiple groups)grep --color=always -C 2 "error" large.log | less -R
# Multiple occurrences show with separatorsgrep -B 1 -A 1 "pattern" file.txt
```

Execution

Terminal window

```
echo -e "line1\nline2\nerror message\nline4\nline5\nerror again\nline7" | grep -B 1 -A 1 "error"
```

Output

Terminal window

```
line2error messageline4--line5error againline7
```

-   Dashes (--) separate different match groups
-   Shows the surrounding log lines for an error
-   Combine with -n for precise line location
-   Better than scrolling through large files

### Invert Match

Show lines NOT matching the pattern

#### Accessibility

Examples of negative matching

#### Best Practices

-   Use -v to filter out known unwanted content
-   Combine with other patterns for precise filtering
-   Use -v to remove comments and blank lines from configs

#### Common Errors

-   **Not getting all non-matching lines:** Verify pattern syntax; test with sample data

#### Keywords

invert\-vnegateexcludenot

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Exclude pattern with -v

The -v flag inverts match, showing only lines NOT starting with 'a'.

Code

Terminal window

```
# -v flag shows lines NOT matching patterngrep -v "pattern" filename
# Useful for filtering out unwanted linesgrep -v "^#" config.txt          # exclude commentsgrep -v "^$" file.txt            # exclude empty linesgrep -v "debug" app.log          # exclude debug logsgrep -v "exclude_this" data.txt  # exclude specific text
```

Execution

Terminal window

```
echo -e "apple\nbanana\napricot\norange" | grep -v "^a"
```

Output

Terminal window

```
orange
```

-   \-v negates the pattern (shows non-matching lines)
-   Useful for filtering out unwanted content
-   Works with any pattern or regex
-   Returns all non-matching lines

#### Multiple inverted patterns

Multiple -v flags exclude both "debug" and "info" lines, leaving only "error" lines.

Code

Terminal window

```
# Stack multiple -v flags to exclude multiple patternsgrep -v 'debug' -v 'info' log.txt
# Exclude multiple patternsgrep -v '^#' -v '^$' config.txt   # no comments, no blank lines
# Combined with other flagsgrep -vn "error" app.log          # exclude errors with line numbersgrep -vic "pattern" file.txt      # case-insensitive invert + count
```

Execution

Terminal window

```
echo -e "debug: test\ninfo: started\nerror: failed\ninfo: complete" | grep -v "^debug" | grep -v "^info"
```

Output

Terminal window

```
error: failed
```

-   Multiple -v flags provide AND logic (exclude all patterns)
-   Different from -e patterns which are OR logic
-   Useful for multi-stage filtering

### Max Count and File Listing

Limit matches and show files with matches

#### Accessibility

Examples of match limiting

#### Best Practices

-   Use -m for quick previews of large files
-   Use -l with xargs for batch operations
-   Use -L to find files missing specific content

#### Common Errors

-   **Missing filenames:** Use -l flag explicitly to get filenames

#### Keywords

max\-mcountfiles\-l\-L

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Limit matches with -m

The -m 2 flag stops after finding 2 matches.

Code

Terminal window

```
# -m NUM flag stops after NUM matchesgrep -m 5 "pattern" filename
# Shows only first N matching linesgrep -m 1 "error" log.txt         # first error onlygrep -m 10 "warning" app.log      # first 10 warnings
# Useful for large files to get quick previewgrep -m 5 "todo" project.txt      # first 5 TODOs
```

Execution

Terminal window

```
echo -e "error1\nerror2\nerror3\nerror4\nerror5" | grep -m 2 "error"
```

Output

Terminal window

```
error1error2
```

-   \-m NUM sets maximum number of matches to display
-   Grep stops reading file after NUM matches
-   Useful for performance on large files
-   Faster than showing all matches and piping to head

#### List files with matches

The -l flag shows only filenames containing the pattern, not the matching lines.

Code

Terminal window

```
# -l flag lists only filenames (one per line) with matchesgrep -l "pattern" *.txt
# -L flag lists only filenames WITHOUT matchesgrep -L "pattern" *.txt
# Useful for finding which files contain/lack contentgrep -r -l "TODO" src/         # files with TODO commentsgrep -r -L "license" docs/     # files without license header
```

Execution

Terminal window

```
echo "test" > /tmp/file1.txt && echo "other" > /tmp/file2.txt && grep -l "test" /tmp/file*.txt
```

Output

Terminal window

```
/tmp/file1.txt
```

-   \-l lists filenames only (helpful for further processing)
-   \-L lists filenames that DON'T match
-   Useful with xargs: grep -l "pattern" \* | xargs cmd
-   Fast because grep stops after the first match

## File and Directory Operations

Search across files and directories

### Recursive Directory Search

Search patterns across multiple files and directories

#### Accessibility

Examples of directory searching

#### Best Practices

-   Use -r for most directory searches
-   Use -R when symlinks must be followed
-   Combine with -n for file location information

#### Common Errors

-   **Searching too slowly:** Use --exclude-dir to skip node\_modules, .git, etc

#### Keywords

recursive\-rdirectoryfilestree

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Recursive search with -r

The -r flag searches recursively through all subdirectories.

Code

Terminal window

```
# -r flag searches directories recursivelygrep -r "pattern" directory/
# Searches all files in directory and subdirectoriesgrep -r "TODO" src/              # find TODOs in codegrep -r "error" logs/            # search all log filesgrep -r "function test" project/ # search all files
# Show filenames with resultsgrep -r -H "pattern" directory/grep -rn "pattern" src/          # with line numbers
```

Execution

Terminal window

```
mkdir -p /tmp/search_test/sub && echo "test line" > /tmp/search_test/file1.txt && echo "test data" > /tmp/search_test/sub/file2.txt && grep -r "test" /tmp/search_test
```

Output

Terminal window

```
/tmp/search_test/file1.txt:test line/tmp/search_test/sub/file2.txt:test data
```

-   \-r searches directories recursively
-   Includes all files in subdirectories
-   Shows filename by default with -r
-   Useful for code search across projects

#### Follow symlinks with -R

The -R flag follows symlinks, so both real and linked paths are searched.

Code

Terminal window

```
# -R flag follows symbolic links (vs -r which doesn't)grep -R "pattern" directory/
# Searches through symlinked directoriesgrep -R "config" /grep -Rn "pattern" src/
# Difference from -r# -r: skip symlinks# -R: follow symlinks (like -r --dereference)
# Exclude patterns for more controlgrep -R --exclude="*.log" "pattern" src/
```

Execution

Terminal window

```
mkdir -p /tmp/test_symlink/real && echo "found" > /tmp/test_symlink/real/file.txt && ln -s real /tmp/test_symlink/link && grep -R "found" /tmp/test_symlink
```

Output

Terminal window

```
/tmp/test_symlink/real/file.txt:found/tmp/test_symlink/link/file.txt:found
```

-   \-R follows symbolic links (-r does not)
-   Important for complex directory structures
-   Can cause infinite loops with circular symlinks
-   Use --exclude-dir to skip problematic directories

### File and Directory Exclusion

Skip specific files and directories from search

#### Accessibility

Examples of file filtering

#### Best Practices

-   Use --exclude-dir for .git, node\_modules, build
-   Use --include for language-specific searches
-   Combine include and exclude for precise control

#### Common Errors

-   **Pattern not found in expected files:** Verify file inclusion/exclusion patterns match correctly

#### Keywords

exclude\--exclude\--exclude-dirincludeskip

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Exclude files by pattern

The --exclude flag skips .log files, showing only the match in file.txt.

Code

Terminal window

```
# --exclude filters specific file patternsgrep -r --exclude="*.log" "pattern" directory/
# Exclude multiple patternsgrep -r --exclude="*.log" --exclude="*.tmp" "pattern" src/
# Exclude directories to speed up searchgrep -r --exclude-dir="node_modules" "pattern" project/grep -r --exclude-dir=".git" --exclude-dir="*.log" "pattern" .
# Common exclusionsgrep -r --exclude-dir=target --exclude-dir=build "pattern" project/
```

Execution

Terminal window

```
mkdir -p /tmp/excl_test && echo "search" > /tmp/excl_test/file.txt && echo "skip" > /tmp/excl_test/file.log && grep -r --exclude="*.log" "search\|skip" /tmp/excl_test
```

Output

Terminal window

```
/tmp/excl_test/file.txt:search
```

-   \--exclude patterns skip specific file types
-   \--exclude-dir skips entire directories
-   Multiple exclusions require separate flags
-   Speeds up searches in large projects

#### Include only specific files

The --include flag searches only .py files, skipping the .java file.

Code

Terminal window

```
# --include filters to specific file patternsgrep -r --include="*.py" "pattern" src/
# Search only specific file typesgrep -r --include="*.js" --include="*.ts" "import" src/
# Combine include and excludegrep -r --include="*.log" --exclude="debug.log" "error" logs/
# More flexible than just excludinggrep -r --include="[Mm]akefile*" "target" .
```

Execution

Terminal window

```
mkdir -p /tmp/incl_test && echo "python" > /tmp/incl_test/script.py && echo "java" > /tmp/incl_test/Main.java && grep -r --include="*.py" "python\|java" /tmp/incl_test
```

Output

Terminal window

```
/tmp/incl_test/script.py:python
```

-   \--include specifies which files to search
-   More precise control than --exclude
-   Multiple includes require separate flags
-   Useful for language-specific searches

### Binary Files and Special Input

Handle binary files and null-separated input

#### Accessibility

Examples of special file handling

#### Best Practices

-   Use -a for searching in binary files cautiously
-   Use -z with find -print0 for safe file handling
-   Skip binary files with --binary-files=without-match in code searches

#### Common Errors

-   **Binary file matches (standard input):** Use -a flag to treat as text, or skip binary files

#### Keywords

binary\-a\-zspecial

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Handle binary files

The -a flag treats input as text even if it contains binary data.

Code

Terminal window

```
# --binary-files specifies how to handle binarygrep --binary-files=text "pattern" binaryfile
# -a flag treats binary as text (like --binary-files=text)grep -a "pattern" binaryfile
# Useful with binary files that contain textgrep -a "version" compiled_binary
# Skip binary files entirelygrep -r --binary-files=without-match "pattern" .
```

Execution

Terminal window

```
echo "Hello binary world" | grep -a "world"
```

Output

Terminal window

```
Hello binary world
```

-   Grep skips binary files by default
-   \-a treats binary input as text characters
-   Useful for searching in compiled binaries
-   May produce garbage output with true binary

#### Null-separated input and output

The -z flag treats null bytes as line separators instead of newlines.

Code

Terminal window

```
# -z flag handles null-separated input/outputgrep -z "pattern" null_separated_file
# Useful with find -print0 for safe handlingfind . -name "*.txt" -print0 | xargs -0 grep "pattern"
# Process filenames with spaces safelyfind . -type f -print0 | xargs -0 grep -z "pattern"
# Combine with other flagsgrep -rz "pattern" directory/
```

Execution

Terminal window

```
printf "line1\0line2\0line3" | grep -z "line2"
```

Output

Terminal window

```
line2
```

-   \-z handles null-delimited input
-   Important for xargs and find with -print0
-   Allows searching paths with special characters
-   Needed for reliable script handling

## Practical Examples and Advanced Usage

Real-world scenarios and complex grep patterns

### Real-World Use Cases

Practical examples of grep in common scenarios

#### Accessibility

Real-world grep usage examples

#### Best Practices

-   Use -n for easy navigation in editors
-   Combine grep with pipes to process results
-   Save complex grep commands as aliases

#### Common Errors

-   **Output is empty or unexpected:** Test pattern on small sample first; check file encoding

#### Keywords

practicalexamplesreal-worlduse-casesscenarios

[Learn more](https://man7.org/linux/man-pages/man1/grep.1.html)

#### Search and analyze log files

Extract specific error types from log entries using piped grep commands.

Code

Terminal window

```
# Count errors in log filegrep -c "ERROR" app.log
# Show recent errors with contextgrep -n -A 2 "ERROR" app.log | tail -20
# Extract specific informationgrep "timestamp:" server.log | grep -o "[0-9:-]*"
# Find patterns across multiple logsgrep -r "Connection refused" var/log/ | sort | uniq
# Get error summarygrep "ERROR" app.log | grep -o "code: [0-9]*" | sort | uniq -c
```

Execution

Terminal window

```
echo -e "2025-02-28 ERROR: db connection\n2025-02-28 ERROR: timeout\n2025-02-28 INFO: OK" | grep "ERROR" | grep -o "ERROR: [a-z]*"
```

Output

Terminal window

```
ERROR: dbERROR: timeout
```

-   Combine grep commands for complex analysis
-   Use grep -o to extract specific data
-   Pipe to sort and uniq for summaries
-   Used for log analysis and debugging

#### Search source code

Find TODO comments in source code with line numbers for quick navigation.

Code

Terminal window

```
# Find function definitionsgrep -rn "^function " src/
# Find TODO and FIXME commentsgrep -r "TODO\|FIXME" src/ --include="*.js"
# Find unused importsgrep -r "^import" src/ | grep -v "from"
# Find break points (in debugging)grep -rn "debugger;" src/
# Search class definitionsgrep -rn "^class " src/ --include="*.js"
```

Execution

Terminal window

```
mkdir -p /tmp/src && echo -e "function test() {}\n// TODO: fix this\nfunction main() {}" > /tmp/src/app.js && grep -n "TODO" /tmp/src/app.js
```

Output

Terminal window

```
2:// TODO: fix this
```

-   Combine patterns for specific code elements
-   Use line numbers for quick editor navigation
-   Useful for code review and cleanup

### Advanced Regular Expression Patterns

Complex regex patterns for specialized searches

#### Accessibility

Advanced regex pattern examples

#### Best Practices

-   Test complex patterns on sample data
-   Use extended regex (-E) for cleaner syntax
-   Use pipes to handle complex logic

#### Common Errors

-   **Lookahead assertions not supported:** Use grep -v with pipes instead of lookahead

#### Keywords

advancedregexpatternscomplexspecialized

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#Extended-regexp)

#### Complex validation patterns

Validates email format using extended regex with character classes and anchors.

Code

Terminal window

```
# Email validation (basic)grep -E "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" emails.txt
# IP address validationgrep -E "^([0-9]{1,3}\.){3}[0-9]{1,3}$" ips.txt
# URL validationgrep -oE "https?://[^ ]+" urls.txt
# Phone number validationgrep -E "^\+?[1-9]\d{1,14}$" phones.txt
# Hexadecimal color codesgrep -oE "#[0-9a-fA-F]{6}" colors.txt
```

Execution

Terminal window

```
echo -e "user@example.com\ninvalid.email\ntest@domain.co.uk" | grep -E "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
```

Output

Terminal window

```
user@example.comtest@domain.co.uk
```

-   Regex validation is pattern-based, not perfect
-   Works well for basic format checking
-   Combine with other tools for stricter validation
-   Test patterns carefully before deployment

#### Negative lookahead and grep

Use pipes to negate patterns that grep doesn't support with lookahead.

Code

Terminal window

```
# Grep doesn't support lookahead, use alternatives# Find lines WITHOUT a pattern (use -v)grep -v "exclude_this" file.txt
# Find lines with pattern but NOT followed by anothergrep "error" file.txt | grep -v "error: handled"
# Complex exclusions with multiple patternsgrep -v "debug\|test\|verbose" app.log
# Lines with pattern A but not pattern Bgrep "function" code.js | grep -v "function test"
```

Execution

Terminal window

```
echo -e "error: critical\nerror: handled\nerror: warning\nerror: critical" | grep "error" | grep -v "error: handled"
```

Output

Terminal window

```
error: criticalerror: warningerror: critical
```

-   Grep doesn't support lookahead/lookbehind assertions
-   Use pipes with -v to achieve similar results
-   Multiple -v flags work with AND logic
-   Adequate for most use cases

### Performance Optimization

Tips for faster grep runs on large files

#### Accessibility

Performance optimization techniques

#### Best Practices

-   Use -F for literal string searches
-   Use -l to find files first, then process
-   Exclude heavy directories to speed up -r searches
-   Use parallel processing for multiple large files

#### Common Errors

-   **Grep is too slow:** Use -F for literals, -m to limit, exclude directories

#### Keywords

performanceoptimizationefficiencylargefiles

[Learn more](https://www.gnu.org/software/grep/manual/grep.html#Performance)

#### Optimize grep performance

Fixed string search (-F) is fastest for literal patterns, useful for large files.

Code

Terminal window

```
# Use fixed string search instead of regex (fastest)grep -F "literal text" large_file.txt
# Use -m to limit results on large filesgrep -m 100 "pattern" huge.log
# Use -l to find files first, then grep specific onesfind . -name "*.log" | xargs grep "pattern"
# Exclude heavy directories earlygrep -r --exclude-dir=node_modules --exclude-dir=.git "pattern" .
# Use word boundaries to eliminate false positivesgrep -w "word" file.txt  # avoids partial matches
```

Execution

Terminal window

```
seq 1 10000 | python3 -c "import sys; print('\n'.join(['test' + str(i) for i in range(10000)]))" | grep -F "test5000"
```

Output

Terminal window

```
test5000
```

-   \-F (fixed string) is much faster than regex
-   \-m limits results for quick previews
-   Exclude unnecessary directories with --exclude-dir
-   Use find | xargs for complex file selection

#### Parallel grep for distributed search

Parallel processing with xargs can speed up searching multiple files.

Code

Terminal window

```
# Use parallel grep on multiple filesfind . -type f -name "*.log" | parallel grep "pattern"
# Or use xargs with multiple jobsfind . -type f | xargs -P 4 grep "pattern"
# Split large file and search partssplit -l 100000 huge.log part_grep "pattern" part_* &
# GNU parallel syntaxls *.log | parallel grep "pattern" {}
```

Execution

Terminal window

```
echo -e "test1\ntest2\ntest3" | xargs -P 2 grep "test"
```

Output

Terminal window

```
test1test2test3
```

-   xargs -P specifies number of parallel processes
-   Most beneficial with hundreds of files
-   GNU parallel is more flexible than xargs
-   Check available CPU before setting job count

Was this useful?

## Tags

#Grep#Search#Pattern Matching#Regular Expressions#Regex#Linux

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Grep&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep&title=Grep&summary=Complete%20grep%20reference%20with%20pattern%20matching%2C%20regular%20expressions%2C%20flags%2C%20context%20options%2C%20and%20practical%20examples%20for%20searching%20text%20files&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Grep%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep&text=Grep "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep&title=Grep "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep&t=Grep "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep&media=&description=Complete%20grep%20reference%20with%20pattern%20matching%2C%20regular%20expressions%2C%20flags%2C%20context%20options%2C%20and%20practical%20examples%20for%20searching%20text%20files "Share on Pinterest")[Email](<mailto:?subject=Grep&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fgrep>)

## Comments

## You might also enjoy

More posts on similar topics

## [Sed](/cheatsheets/sed)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

This sed reference covers basic text substitution through advanced scripting techniques, with practical examples for text processing, file editing, and automation.

#Sed#Stream Editor#Text Transformation+3 tags

[read more](/cheatsheets/sed)

## [Chmod](/cheatsheets/chmod)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Management
-   Tools

Complete chmod reference covering file permissions, recursive changes with -v and -c, reference mode, logical operators, batch operations, practical examples, and security best practices for Linux fil

#Chmod#Permissions#File Permissions+5 tags

[read more](/cheatsheets/chmod)

## [Find](/cheatsheets/find)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Operations
-   Tools

Best practices for find command usageAlways quote patterns to prevent shell expansion of special characters Use -type f first in find expressions for optimal performance \*\*Prune hea

#Find#File Search#Discovery+3 tags

[read more](/cheatsheets/find)

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

## [Cron](/cheatsheets/cron)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Scheduling
-   Automation
-   Tools

Quick reference Field layout Min Hour Day Month Weekday Command\* /path/to/command ┬ ┬ ┬ ┬ ┬ │ │ │ │ └───── Weekday (0=Sunday,

#Cron#Crontab#Scheduling+3 tags

[read more](/cheatsheets/cron)

## [Netstat](/cheatsheets/netstat)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Networking
-   Tools

This netstat cheatsheet covers six categories, with worked examples and troubleshooting steps in each.

#Netstat#Network#Connections+3 tags

[read more](/cheatsheets/netstat)

6 related posts
