grep Search text lines
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
grep "<text>" <file>
grep -i "<text>" <file>
grep -rn "<text>" <dir>
grep -v "<text>" <file>
grep -C 3 "<text>" <file>
grep -E "<a>|<b>" <file>
grep -c "<text>" <file>
grep -l "<text>" <files>
Concepts
- Input files or stdin
- Match per line
- Select -v, -m, -w, -x
- Output -n, -o, -c, -l
Matching
grep "<pattern>" <file>
grep -i "<pattern>" <file>
grep -v "<pattern>" <file>
grep -w "<word>" <file>
grep -x "<line>" <file>
grep -F "<text>" <file>
grep -E "<a>|<b>" <file>
grep -e <a> -e <b> <file>
grep -f <patterns> <file>
grep -P "<regex>" <file>
grep -m <n> "<pattern>"
<file>
grep -e "-v" <file>
Output
grep -n "<pattern>" <file>
grep -c "<pattern>" <file>
grep -l "<pattern>" <files>
grep -L "<pattern>" <files>
grep -o "<regex>" <file>
grep -q "<pattern>" <file>
grep -H "<pattern>" <file>
grep -h "<pattern>" <files>
grep -b "<pattern>" <file>
grep --color=always "<pattern>"
<file>
grep -s "<pattern>" <files>
grep -Z -l "<pattern>" <files>
Context
grep -A <n> "<pattern>"
<file>
grep -B <n> "<pattern>"
<file>
grep -C <n> "<pattern>"
<file>
grep --no-group-separator -C 2 "<p>"
<f>
| Sign | Meaning |
|---|---|
file:12: |
matching line |
file-12- |
context line |
-- |
gap between groups |
Files & Recursion
grep -r "<pattern>" <dir>
grep -R "<pattern>" <dir>
grep -r --include="*.py" "<p>"
<dir>
grep -r --exclude="*.min.js" "<p>"
.
grep -r --exclude-dir=<dir> "<p>"
.
grep -I "<pattern>" <files>
grep -a "<pattern>" <file>
grep "<pattern>" -
grep -z "<pattern>" <file>
Regex syntax
| Syntax | Matches |
|---|---|
. |
any one character |
* |
zero or more of previous |
^ $ |
start / end of line |
[abc] [^abc] |
one of / none of |
[a-z] |
a range |
[[:digit:]] |
POSIX class |
\< \> |
word start / end |
\b |
word boundary |
| Syntax | Matches |
|---|---|
a|b |
a or b |
( ) |
group |
+ |
one or more |
? |
zero or one |
{n,m} |
n to m repeats |
\1 |
back-reference to group 1 |
grep -P "\d+" <file>
grep -oP "<before>\K<value>"
<file>
grep -P "<a>(?=<b>)" <file>
grep -E "^(.).*\1$" <file>
Recipes
grep -rnw --include="*.c" "<name>" src/# add --exclude-dir=build to skip output
ps aux | grep "[n]ginx"# [n] stops grep from matching itself
grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log | sort | uniq -c | sort -rn | head
if grep -q "^<user>:" /etc/passwd; then echo "user exists"fi
grep -rl "<a>" . | xargs grep -L "<b>"



