Skip to content

grep command

Search text for lines that match a pattern.

On this page

Syntax

grep [options] pattern [file…]

Provided by the grep package. Run man grep for the full manual.

Common options

OptionWhat it does
-iIgnore case
-rSearch directories recursively
-nShow line numbers
-vShow lines that don't match
-wMatch whole words only
-cCount matching lines
-lOnly list file names with a match
-EExtended regex (|, +, ? without escaping)
-oPrint only the matched part
-A N / -B N / -C NShow N lines after / before / around each match
--include=GLOBOnly search matching file names

Examples

  1. Search a file

    grep "error" /var/log/syslog
  2. Ignore case

    grep -i "warning" app.log
  3. Search a directory recursively

    grep -rn "DB_PASSWORD" /var/www/
  4. Only list files that match

    grep -rl "TODO" src/
  5. Lines that do not match

    grep -v "^#" /etc/ssh/sshd_config
  6. Count matches

    grep -c "404" access.log
  7. Several words at once

    grep -E "error|fail|critical" app.log
  8. Show 3 lines around each match

    grep -C 3 "Exception" app.log
  9. Only in .php files

    grep -rn --include="*.php" "mysqli_connect" .
  10. Remove comments and blank lines

    grep -Ev "^\s*(#|$)" nginx.conf
  11. Print only the matched text

    grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log

Tips

  • egrep is the same as grep -E and is deprecated.

grep guides

← All Linux commands · Suggest a fix

Back to top