grep
ShellFundamentals In simulator In real LinuxSearch 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-case | Ignore case |
| -v / --invert-match | Invert: show non-matching lines |
| -w / --word-regexp | Match whole words only |
| -x / --line-regexp | The whole line must match |
| -n / --line-number | Show line numbers |
| -c / --count | Print only a count of matching lines |
| -o / --only-matching | Print only the matching part, not the whole line |
| -l / --files-with-matches | Print only names of files with matches |
| -L / --files-without-match | List only the files without a match |
| -h / --no-filename | With several files, leave the file names out |
| -r / --recursive | Search directories recursively |
| -E / --extended-regexp | Extended regular expressions (|, +, ? …) |
| -F / --fixed-strings | Take the pattern as plain text, not a regular expression (for . * [ ) |
| -P / --perl-regexp | Use Perl-style regular expressions (\d, \w, lazy *? …) |
| -e / --regexp PATTERN | The pattern (for one that starts with -, or several patterns) |
| -f / --file FILE | Read patterns from FILE, one per line |
| -A / --after-context NUM | Also show NUM lines after each match |
| -B / --before-context NUM | Also show NUM lines before each match |
| -C / --context NUM | Also show NUM lines around each match |
| -m / --max-count NUM | Stop after NUM matches |
| -q / --quiet | Print nothing; the exit status says whether it matched (for if) |
| --include GLOB | With -r: search only files matching GLOB, e.g. --include="*.py" |
| --exclude GLOB | With -r: skip files matching GLOB |
| --exclude-dir GLOB | With -r: skip these directories, e.g. --exclude-dir=.git |
| --color WHEN | Highlight 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