Skip to content

Linux Foundations / Find your way around Linux ยท Step 46 of 63

Lesson: grepSwitch
โ† Linux Foundations

Shell and files

grep

Learn to search text for matching lines with grep and basic regular expressions.

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 full

The form is grep PATTERN FILE. It also reads stdin, so it works after a pipe: ps aux | grep ssh.

Useful options

  • -i ignore case
  • -v print lines that do not match
  • -n show line numbers
  • -c count matching lines
  • -w match 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 retry

Note 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 full

Quote 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 retry

Search directories

-r searches all files under a directory.

$ grep -rn "Port" /etc/ssh

The 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 found

Keep going in the search and archives lab.

Try it

  1. Run grep root /etc/passwd.
  2. Add -n, then try -c.
  3. Show lines that do not contain nologin with grep -v nologin /etc/passwd.
  4. Find lines starting with r using grep '^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.