Home·Terminal commands

grep

Text processing

Usage

grep -rn '[pattern]' [path]

Picks the lines that match a pattern; it reads basic regex by default, so + ? | and () need -E or a backslash to keep their meaning.

Common flags

FlagMeaning
-iIgnore case
-rSearch a whole directory tree; -R also follows symlinks
-nPrint the line number of each hit
-vInvert: print the lines that do not match
-lPrint only the names of the files that matched
-wMatch whole words only
-EExtended regex, so + ? | and () work unescaped
-CPrint N lines of context around each hit

Examples

grep -rn 'TODO' src/

Every TODO in the tree, with file and line.

grep -v '^#' nginx.conf

Drops the comment lines.

ps aux | grep '[n]ginx'

Finds nginx without matching the grep itself.

These were built to be piped together. Three joined commands are usually shorter than one that does everything.

How to read this

  • Square brackets [ ] mark a part you may leave out.
  • An ellipsis … means you can list more than one.
  • Flags are case-sensitive — in some commands -r and -R do different things.

Questions

Q. What does grep do?

Picks the lines that match a pattern; it reads basic regex by default, so + ? | and () need -E or a backslash to keep their meaning.

Q. How do I type it?

grep -rn '[pattern]' [path] — square brackets mark the parts you can leave out.

Q. How many flags are worth knowing?

8 are listed here; the full set is in man grep. This command sits under Text processing.

Related commands

man page: man grep