grep(1)
Search for lines matching a pattern in files or stdin.
Synopsis
grep [OPTION]... PATTERN [FILE]...Description
grep searches for lines in input files that match a given pattern and prints them to standard output. The pattern can be a simple string or a regular expression. If no files are specified, grep reads from standard input.
By default, grep treats the pattern as a basic regular expression. Use -E for extended regex or -F to treat the pattern as a fixed string literal.
Common options
| Flag | What it does |
|---|---|
-i | case-insensitive search |
-v | invert match—print lines that do NOT match the pattern |
-n | print line numbers with output |
-c | count matching lines instead of printing them |
-l | print only filenames with matches |
-r | recursively search directories |
-E | use extended regular expressions (same as egrep) |
-F | treat pattern as a fixed string, not regex |
-w | match only whole words |
-o | print only the matched part, not the whole line |
-A NUM | print NUM lines of context after each match |
-B NUM | print NUM lines of context before each match |
Examples
Find all lines containing 'error' in the syslog file
grep 'error' /var/log/syslogCase-insensitive search for 'warning' and show first 20 results
grep -i 'warning' /var/log/syslog | head -20Show line numbers of all comments (lines starting with #)
grep -n '^#' /etc/ssh/sshd_configRemove comment and blank lines to see active configuration
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'Recursively search all files in a directory for 'TODO' markers
grep -r 'TODO' /home/user/projects/Count how many times 'failed' appears in the auth log
grep -c 'failed' /var/log/auth.logFind 'cat' as a whole word (not 'catch' or 'catalog')
grep -w 'cat' /usr/share/dict/wordsFind lines with IPv4 addresses using extended regex
grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' /tmp/ips.txt