Back to the command reference

grep

ShellFundamentals In simulator In real Linux

Search text for a pattern

Name: grep = global regular expression print, from the ed command g/re/p

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

grep searches files or standard input line by line for a pattern (a regular expression) and prints matching lines. Basic regular expressions are the default; -E uses extended ones and -F treats the pattern as a fixed string.

Exit status: 0 when something matched, 1 when nothing did, 2 on error, which is why grep -q is common in shell if statements.

Syntax

grep [OPTION]... PATTERN [FILE]...

Common options

-i / --ignore-caseIgnore case
-v / --invert-matchInvert: show non-matching lines
-w / --word-regexpMatch whole words only
-x / --line-regexpThe whole line must match
-n / --line-numberShow line numbers
-c / --countPrint only a count of matching lines
-o / --only-matchingPrint only the matching part, not the whole line
-l / --files-with-matchesPrint only names of files with matches
-L / --files-without-matchList only the files without a match
-h / --no-filenameWith several files, leave the file names out
-r / --recursiveSearch directories recursively
-E / --extended-regexpExtended regular expressions (|, +, ? …)
-F / --fixed-stringsTake the pattern as plain text, not a regular expression (for . * [ )
-P / --perl-regexpUse Perl-style regular expressions (\d, \w, lazy *? …)
-e / --regexp PATTERNThe pattern (for one that starts with -, or several patterns)
-f / --file FILERead patterns from FILE, one per line
-A / --after-context NUMAlso show NUM lines after each match
-B / --before-context NUMAlso show NUM lines before each match
-C / --context NUMAlso show NUM lines around each match
-m / --max-count NUMStop after NUM matches
-q / --quietPrint nothing; the exit status says whether it matched (for if)
--include GLOBWith -r: search only files matching GLOB, e.g. --include="*.py"
--exclude GLOBWith -r: skip files matching GLOB
--exclude-dir GLOBWith -r: skip these directories, e.g. --exclude-dir=.git
--color WHENHighlight matches: auto, always or never

Examples

  • $ grep ERROR logs/app.log

    Lines containing ERROR

    Explain
  • $ grep -in "error" logs/app.log

    Case-insensitive, with line numbers

    Explain
  • $ grep -c apple data/fruits.txt

    Count lines containing apple

    Explain
  • $ grep -r "Hello" projects

    Search a whole directory

    Explain
  • $ ps -ef | grep nginx

    Find nginx in the process list

    Explain

Related