grep searches input and prints every line that matches a pattern. It is one of the tools you will use most.
Basic search
$ cat app.log
INFO start
ERROR disk full
info retry
$ grep ERROR app.log
ERROR disk fullThe form is grep PATTERN FILE. It also reads stdin, so it works after a pipe: ps aux | grep ssh.
Useful options
-iignore case-vprint lines that do not match-nshow line numbers-ccount matching lines-wmatch whole words only
$ grep -i info app.log
INFO start
info retry
$ grep -n ERROR app.log
2:ERROR disk full$ grep -v ERROR app.log
INFO start
info retryNote that -c counts lines, not occurrences. A line with the word twice counts once.
Patterns
Patterns are regular expressions. ^ means start of line, $ means end of line, . means any single character, and * means the previous item zero or more times.
$ grep '^ERR' app.log
ERROR disk full
$ grep 'full$' app.log
ERROR disk fullQuote the pattern so the shell does not interpret it.
-E enables extended syntax, where | means "or". -F treats the pattern as plain text, so a dot is just a dot.
$ grep -E 'ERROR|retry' app.log
ERROR disk full
info retrySearch directories
-r searches all files under a directory.
$ grep -rn "Port" /etc/sshThe result depends on your system, and some files may need sudo.
Exit status
grep returns 0 if it found a match, 1 if it did not, and 2 if an error occurred. -q stays quiet, which is ideal in scripts.
$ grep -q ERROR app.log && echo "problem found"
problem foundKeep going in the search and archives lab.
Try it
- Run
grep root /etc/passwd. - Add
-n, then try-c. - Show lines that do not contain
nologinwithgrep -v nologin /etc/passwd. - Find lines starting with
rusinggrep '^r' /etc/passwd.
Check your understanding
grep
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.