grep

text processinglinux
The grep command is one of the most frequently used commands in Linux/Unix-like operating systems. grep The grep command is used to search for text patterns in files. It's a powerful tool for finding specific content in files or filtering command output based on regular expressions or string patterns.

Quick Reference

Command Name:

grep

Category:

text processing

Platform:

linux

Basic Usage:

grep "pattern" filename.txt

Common Use Cases

    Syntax

    grep [options] pattern [file...]

    Options

    Option Description
    -i, --ignore-case Ignore case distinctions in patterns and input data
    -v, --invert-match Select non-matching lines
    -w, --word-regexp Match only whole words
    -r, --recursive Read all files under each directory recursively
    -n, --line-number Prefix each line of output with its line number
    -l, --files-with-matches Print only names of files with matching lines
    -L, --files-without-match Print only names of files with no matching lines
    -c, --count Print only a count of matching lines per file
    -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines
    -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines
    -C NUM, --context=NUM Print NUM lines of context before and after matches
    -E, --extended-regexp Use extended regular expressions
    -F, --fixed-strings Interpret patterns as fixed strings, not regular expressions
    -P, --perl-regexp Interpret patterns as Perl-compatible regular expressions
    --include=GLOB Search only files that match GLOB pattern
    --exclude=GLOB Skip files that match GLOB pattern
    --color[=WHEN] Surround matches with color markers (auto, always, never)
    -o, --only-matching Show only the part of a line that matches the pattern
    -q, --quiet, --silent Suppress all normal output (exit with status 0 if match found)

    Examples

    How to Use These Examples

    The examples below show common ways to use the grep command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.

    #

    Basic Examples:

    grep "error" logfile.txt

    Searches for the word "error" in logfile.txt. This is the most basic usage of grep that displays all lines containing the specified pattern.

    grep -i "warning" logfile.txt

    Performs a case-insensitive search for "warning" in logfile.txt. The -i option ignores case distinctions, matching both "Warning", "WARNING", and "warning".

    grep -r "TODO" /path/to/project

    Recursively searches for "TODO" in all files under the specified directory. The -r option enables recursive searching through all subdirectories.

    grep -v "error" logfile.txt

    Inverts the match, showing all lines that do NOT contain "error". The -v option inverts the sense of matching, selecting non-matching lines.

    Advanced Examples:

    grep -E "error|warning|critical" logfile.txt

    Searches for multiple patterns using regular expressions. The -E option enables extended regular expressions, allowing the use of the OR operator (|) to match any of the specified patterns.

    grep -n "function" script.js

    Shows line numbers for matching lines. The -n option prefixes each matching line with its line number, making it easier to locate the match in the file.

    grep -l "error" *.log

    Lists only the filenames of matching files. The -l option shows only the names of files containing matches, rather than the matching lines themselves.

    grep -A 2 -B 2 "Exception" application.log

    Shows context around matching lines. The -A 2 option displays 2 lines after the match, and -B 2 displays 2 lines before the match, providing context for each occurrence.

    cat logfile.txt | grep "error" | grep -v "false alarm"

    Pipes output between commands for complex filtering. This pipeline first extracts lines containing "error", then removes lines that also contain "false alarm", demonstrating how grep can be used in command chains.

    grep -c "login failed" auth.log

    Counts matching lines instead of displaying them. The -c option only outputs a count of matching lines, useful for quick statistics without seeing the actual content.

    Try It Yourself

    Practice makes perfect! The best way to learn is by trying these examples on your own system with real files.

    Understanding Syntax

    Pay attention to the syntax coloring: commands, options, and file paths are highlighted differently.

    Notes

    How 'grep' Works:

    • The grep command searches for patterns in each file or standard input
    • It reads each line and outputs those lines that contain the specified pattern
    • By default, the matching is case-sensitive but can be modified with options
    • When multiple files are specified, grep outputs the filename before each matched line

    Common Use Cases:

    • Searching for specific text in log files
    • Filtering command output for relevant information
    • Finding specific code patterns in source files
    • Counting occurrences of patterns in files
    • Locating files containing specific content
    • Extracting data from structured text files

    Regular Expression Support:

    • Basic regular expressions (BRE) are supported by default
    • Extended regular expressions (ERE) are enabled with -E
    • Perl-compatible regular expressions (PCRE) are available with -P
    • Fixed-string matching (no regular expressions) with -F
    • Common regex patterns: ^ (line start), $ (line end), . (any char), * (zero or more), [ ] (character class)

    Performance Tips:

    • Use -F for faster searches when looking for fixed strings
    • Use --include or --exclude to limit file types in recursive searches
    • For faster recursive searching in large directory structures, consider using find with -exec grep
    • For very large files, tools like awk or sed might be more efficient
    • Use -l to just list matching files instead of displaying all matches

    Practical Tips:

    • Combine grep with | (pipe) to filter output from other commands
    • Use grep -v to exclude lines matching a pattern
    • Quote patterns to prevent shell interpretation of special characters
    • Use -A, -B, and -C to see context around matches
    • Enable --color to highlight matched text in terminal output

    Related Commands:

    • egrep - Equivalent to grep -E
    • fgrep - Equivalent to grep -F
    • rgrep - Equivalent to grep -r
    • sed - Stream editor that can search and replace text
    • awk - Pattern scanning and text processing language
    • find - Search for files in a directory hierarchy

    Related Commands

    awk

    awk

    View command

    sed

    sed

    View command

    cat

    cat

    View command

    find

    find

    View command

    xargs

    xargs

    View command

    Learn By Doing

    The best way to learn Linux commands is by practicing. Try out these examples in your terminal to build muscle memory and understand how the grep command works in different scenarios.

    $ grep
    View All Commands