$linuxjunkies
>

grep(1)

Search for lines matching a pattern in files or stdin.

UbuntuDebianFedoraArch

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

FlagWhat it does
-icase-insensitive search
-vinvert match—print lines that do NOT match the pattern
-nprint line numbers with output
-ccount matching lines instead of printing them
-lprint only filenames with matches
-rrecursively search directories
-Euse extended regular expressions (same as egrep)
-Ftreat pattern as a fixed string, not regex
-wmatch only whole words
-oprint only the matched part, not the whole line
-A NUMprint NUM lines of context after each match
-B NUMprint NUM lines of context before each match

Examples

Find all lines containing 'error' in the syslog file

grep 'error' /var/log/syslog

Case-insensitive search for 'warning' and show first 20 results

grep -i 'warning' /var/log/syslog | head -20

Show line numbers of all comments (lines starting with #)

grep -n '^#' /etc/ssh/sshd_config

Remove 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.log

Find 'cat' as a whole word (not 'catch' or 'catalog')

grep -w 'cat' /usr/share/dict/words

Find 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

Related commands