Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
Wat het doet
grep prints every line that contains a match. It is the main tool to search logs, config files and command output. The pattern is a regular expression: basic (default), extended (-E), fixed text (-F) or Perl style (-P).
egrep and fgrep are old names for grep -E and grep -F.
Exit codes: 0 = something matched, 1 = nothing matched, 2 = an error. Scripts use this with -q.
Zo schrijf je het
grep [OPTION...] PATTERNS [FILE...]
grep [OPTION...] -e PATTERNS ... [FILE...]
grep [OPTION...] -f PATTERN_FILE ... [FILE...]Opties 48
Meest gebruikt
Pattern type
Matching
Output
Context
Files and folders
Niets past bij dit filter.
Voorbeelden 14
$ als gewone gebruiker# als root (of met sudo)
1Find a user in the passwd file
grep student /etc/passwdEvery line that contains "student".
2Search a log, ignore case
grep -i error /var/log/messagesFinds Error, ERROR and error.
3Search all files in a folder, with line numbers
grep -rn "PermitRootLogin" /etc/ssh/File name, line number and the line.
4Show the active settings (no comments, no empty lines)
grep -Ev '^\s*(#|$)' /etc/ssh/sshd_configOne command instead of two greps.
5Count matches
grep -c "Failed password" /var/log/secureNumber of failed SSH logins in the file.
6Search for several words
grep -E 'error|fail|denied' /var/log/messages grep -e error -e fail /var/log/messagesTwo ways to search for "this OR that".
7Show lines around a match
grep -B3 -A5 "Out of memory" /var/log/messagesContext shows what happened before and after.
8Only list the files that contain the text
grep -rl "192.168.122.10" /etc 2>/dev/nullFind every config that still uses an old IP address.
9Print only the matching part (extract IPs)
The IP addresses that appear most in the log.
10Whole words only
grep -w root /etc/passwdMatches "root" but not "chroot".
11Use grep in an if test
if grep -q '^student:' /etc/passwd; then echo "user exists"; fi-qprints nothing; the exit code decides.12Search only some file types
grep -rn --include='*.yaml' --exclude-dir=.git "image:" .All container images used in a repo.
13Find secrets before a commit
grep -rniE '(password|secret|api[_-]?key)\s*[:=]' --exclude-dir=.git .A quick check; real projects use tools like gitleaks.
14Search compressed rotated logs
zgrep "Accepted publickey" /var/log/secure-*.gzSame options as grep, on .gz files.
Niets past bij dit filter.
Let op
- Put the pattern in single quotes, or the shell may change
*,$,\or|first. grep pattern file > fileempties the file. Write to a new file.- A dot means "any character": use
\.or-Ffor a real dot (IP addresses!).
Tips om te onthouden
- i = ignore case, v = invert, r = recursive, n = numbers, c = count, l = list files, w = word, E = extended, o = only match.