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
| Flag | Meaning |
|---|---|
| -i | Ignore case |
| -r | Search a whole directory tree; -R also follows symlinks |
| -n | Print the line number of each hit |
| -v | Invert: print the lines that do not match |
| -l | Print only the names of the files that matched |
| -w | Match whole words only |
| -E | Extended regex, so + ? | and () work unescaped |
| -C | Print N lines of context around each hit |
Examples
grep -rn 'TODO' src/Every TODO in the tree, with file and line.
grep -v '^#' nginx.confDrops 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