Skip to main content

grep

Explanation

The grep command searches for patterns in each file. Patterns can be simple strings or complex regular expressions. It prints each line that matches a pattern. grep is an essential tool for parsing logs, finding specific code, or filtering output from other commands.

Basic Syntax

grep [OPTION]... PATTERNS [FILE]...

Common Flags and Options

FlagDescription
-i, --ignore-caseIgnore case distinctions in patterns and input data.
-v, --invert-matchSelect non-matching lines.
-r, -R, --recursiveRead all files under each directory, recursively.
-n, --line-numberPrefix each line of output with the 1-based line number.
-l, --files-with-matchesPrint only names of FILEs containing matches.
-c, --countPrint only a count of selected lines per FILE.

Real-world Examples

  1. Search for a string in a file:

    grep "error" /var/log/syslog
  2. Search case-insensitively for a pattern:

    grep -i "warning" mylog.txt
  3. Search for a pattern recursively in a directory:

    grep -r "TODO" src/