Lab 7: Grep with RegEx
Objective Focus
- Understand and use essential tools
- Use grep and regular expressions to analyze text
Official RHCSA EX200 Exam Objectives
To begin, I want to point out the importance of focusing on the official objectives. Grep is a powerful tool and it can get complex quickly. Remember, the main thing is to gain familiarity with the tool and where to find help docs (aka Manual Pages). That will help keep us on track with passing the EX200.
Grep helps us print lines that match patterns!
Regular Expression Basics
grep uses basic regular expressions by default.
Character | Meaning |
---|---|
. (dot) | Matches any single character (except newline) |
(asterisk) * | Matches zero or more occurrences of the preceding character or group |
^ (caret) | Matches the beginning of a line |
$ (dollar sign) | Matches the end of a line |
[] (square brackets) | Matches any single character within the brackets. You can use ranges like [a-z] for lowercase letters and [1-8] for numbers |
[^] (caret inside brackets) | Matches any single character not within the brackets |
\ (backslash) | Escapes special characters, allowing you to match them literally ( example . matches a literal dot) |
Download sample log to follow along
here!
Basic Grep Syntax
$ grep [OPTION...] [PATTERNS] [FILE...]
- Syntax for grep command
$ grep 'ERROR' sample_sysinfo.log
- Match for exact occurrence of ‘ERROR’, grep is case sensitive
$ grep '^2024-12-11' sample_sysinfo.log
- Match start of a line (^)
$ grep 'ted$' sample_sysinfo.log
- Match end of a line ($)
$ grep '..:00:00' sample_sysinfo.log
- Match any single character (.)
$ grep '10:[3-5]' sample_sysinfo.log
- Character classes [a-zA-Z] [0-9]
Options I use often
Option | Action |
---|---|
-i | Ignore case |
-r or -R | Search recursively in directories |
-v | Invert the match, show lines that do not match the pattern. |
-n | Show line numbers of matching lines |
-l | Show only the filename with matches |
-o | Show only the matching part of line |
For now, that’s all for Grep!