grep & regular expressions
Search text with grep, its most useful options, and basic and extended regular expressions.
grep searches text for lines matching a pattern. It's one of the most-used commands on any Linux machine: digging through logs, finding where a function is defined, checking a config setting, filtering the output of other commands. Paired with regular expressions, it becomes a precision tool.
Sample log (app.log) used throughout:
The basics#
grep prints every line containing the pattern. It's case-sensitive, so the lowercase error line was skipped. The most useful options:
Context is gold when debugging:
Searching many files#
grep in a script uses its exit status: 0 if something matched, 1 if not.
And it's the universal filter at the end of a pipe: ps aux | grep nginx, dpkg -l | grep python3, history | grep ssh.
Regular expressions#
A regular expression (regex) is a pattern language. grep understands two dialects: basic (the default) and extended (grep -E). Use -E; it needs fewer backslashes.
Regex
*is not the shell's*. In a regex,*means "repeat the previous thing"; "anything" is.*.
Practical patterns
The email regex reads: one or more allowed characters, an @, a domain, a literal dot (\.) and at least two letters. (Real-world email validation is harder; this is good enough for searching logs.)
Some more you'll reuse:
The first one is a sysadmin favourite: it shows only the settings that are actually active.
Literal text with -F
When you search for text that contains regex characters, like 1.2.3 or [error] or $PATH, use -F so nothing is special:
Always single-quote patterns that contain $, *, | or \, so the shell leaves them alone.
Beyond grep: ripgrep#
For searching large codebases, ripgrep (rg) is a popular faster alternative: recursive by default, respects .gitignore and skips binary files. Install it with sudo apt install ripgrep (Fedora: sudo dnf install ripgrep) and use it like rg TODO or rg -i "connection refused" /var/log.
Common mistakes#
- Forgetting
-Eand wondering why+,?or|don't work. - Using the shell's
*meaning inside a regex (grep "*.log"). - Not escaping the dot:
grep "1.5"also matches105and1x5. ps aux | grep nginxalso lists the grep process itself. Usepgrep -a nginx, or the trickgrep [n]ginx.- Searching binary or huge directories without
--exclude-dir.
What's next#
grep becomes even more powerful when you chain it with other commands. Next: pipes and redirection, covering stdin, stdout and stderr, |, >, 2>&1, tee and xargs.
Check your understanding
Quick quiz
1.Which command lists only the NAMES of files under
src/that contain the word TODO?2.In a regular expression, what does
^ERRORmatch?3.Why does
grep -E 'ERROR|WARN' app.logwork, whilegrep 'ERROR|WARN' app.logusually finds nothing?
Finished reading?
Mark this lesson complete to track your progress.