Study guide
6.6 Regular Expressions & grep, egrep, fgrep (103.7)
LPIC-1 Linux Administrator — Exam 101 101-500
Track your progress as you read
Finished sections get a check mark.
1 Exam Overview & Study Strategy
1.1 LPIC-1 101-500 Exam Structure & Blueprint 1.2 Command Line & Shell Fundamentals for Exam Success 1.3 Fill-in-the-Blank Strategies & Common Traps
2 Topic 101: System Architecture
2.1 Hardware Discovery, Sysfs, Procfs & Kernel Modules (101.1) 2.2 Udev, Dbus & Device Management (101.1) 2.3 BIOS vs. UEFI & System Boot Process (101.2) 2.4 Kernel Initialization, Initramfs & System Logs (101.2) 2.5 Systemd Boot Targets & Unit Management (101.3) 2.6 SysVinit Runlevels, Telinit & System Shutdown (101.3)
3 Topic 102: Linux Installation & Boot Management
3.1 Hard Disk Layout, Partition Schemes & Swap Design (102.1) 3.2 LVM & Standard Mount Point Allocation (102.1) 3.3 GRUB 2 Configuration & Troubleshooting (102.2) 3.4 Legacy GRUB & Alternative Boot Loaders (102.2) 3.5 Managing Shared Libraries & ldconfig (102.3) 3.6 Linux as a Virtualization Guest & Cloud Instances (102.6)
4 Topic 102: Package Management Systems
4.1 Debian Low-Level Package Management with dpkg (102.4) 4.2 High-Level Debian Package Management: apt, apt-get & apt-cache (102.4) 4.3 RPM Package Management with rpm (102.5) 4.4 YUM, DNF & Zypper Package Management (102.5) 4.5 Package Repositories & Integrity Verification (102.4/102.5) 4.6 Universal Linux Packages: Snap, Flatpak & AppImage (102.4/102.5)
5 Topic 103: Command Line & Text Processing
5.1 Shell Environment, Environment Variables & Aliases (103.1) 5.2 Command History, Quoting & Expansion (103.1) 5.3 Basic Text Filters: cat, head, tail, cut, paste, nl, od (103.2) 5.4 Advanced Text Filters: sort, uniq, wc, tr, split, less & Checksums (103.2) 5.5 Stream Editing with sed (103.2) 5.6 Basic File Management: cp, mv, rm, touch, mkdir, rmdir (103.3) 5.7 Archiving and Compression: tar, gzip, bzip2, xz, cpio & dd (103.3)
6 Topic 103: Streams, Processes, Regex & Vi
6.1 Standard Streams, Redirection & File Descriptors (103.4) 6.2 Pipelines, tee & xargs (103.4) 6.3 Process Monitoring: ps, top, free, watch, pgrep, pstree & uptime (103.5) 6.4 Signals, kill, Job Control, nohup, screen & tmux (103.5) 6.5 Process Priorities: nice & renice (103.6) 6.6 Regular Expressions & grep, egrep, fgrep (103.7) 6.7 vi / vim Modes, plus nano, Emacs & EDITOR Awareness (103.8)
7 Topic 104: Devices, Partitions & Filesystems
7.1 Block Devices, fdisk & gdisk (104.1) 7.2 GNU Parted & Partition Table Management (104.1) 7.3 Creating Filesystems: mkfs, ext4, XFS, VFAT/exFAT & Btrfs (104.1) 7.4 Filesystem Integrity: fsck, e2fsck, xfs_repair, xfs_fsr & xfs_db (104.2) 7.5 Monitoring Disk Usage: df, du & tune2fs (104.2) 7.6 Managing Swap Space: mkswap, swapon & swapoff (104.1/104.2)
8 Topic 104: Mounts, Permissions, Links & FHS
8.1 Mounting and Unmounting Filesystems: mount & umount (104.3) 8.2 Persistent Mounts: /etc/fstab, UUIDs & systemd mount units (104.3) 8.3 Standard File Permissions: chmod, chown, chgrp & umask (104.5) 8.4 Special Permissions: SUID, SGID & Sticky Bit (104.5) 8.5 Hard Links vs. Symbolic Links: ln & Inodes (104.6) 8.6 Filesystem Hierarchy Standard (FHS) & File Location (104.7)
6.6 Regular Expressions & grep, egrep, fgrep (103.7)
Key Takeaways Explain This Topic AI
Regular expressions fall into two primary POSIX standards: Basic Regular Expressions (BRE, default in grep and sed ) and Extended Regular Expressions (ERE, enabled via grep -E or egrep ).
In BRE, metacharacters + , ? , {n,m} , ( ) , and | must be escaped with a backslash ( \+ , \? , \{n,m\} , \( \) , \| ) to activate special meaning; in ERE, they function as metacharacters natively.
Line anchors match text boundaries: ^ matches line beginning, $ matches line ending, and ^$ matches empty lines.
POSIX character classes (e.g. [[:alnum:]] , [[:digit:]] , [[:space:]] ) provide locale-independent character matching inside bracket expressions.
The grep family includes grep (BRE), egrep / grep -E (ERE), and fgrep / grep -F (fixed literal strings, bypassing regex compilation for maximum throughput).
Last updated: August 2026
6.6 Regular Expressions & grep, egrep, fgrep
Quick Summary: Regular Expressions (Regex) provide a formal pattern-matching grammar for scanning, parsing, and filtering text streams in Linux. POSIX defines two primary dialects: Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE) . Administrators use the grep family—comprising standard grep (BRE), egrep / grep -E (ERE), and fgrep / grep -F (fixed literal string matching)—to locate log patterns, extract configuration parameters, and audit system files.
1. Regular Expression Flavors: BRE vs. ERE
The fundamental distinction between Basic and Extended Regular Expressions lies in how metacharacters and quantifiers are interpreted by default.
Regex Feature Metacharacter Basic Regular Expression (BRE) Syntax Extended Regular Expression (ERE) Syntax Functional Matching Definition
Any Character . . . Matches any single character except newline ( \n ).
Line Start Anchor ^ ^ ^ Matches the position immediately at the beginning of a line.
Line End Anchor $ $ $ Matches the position immediately at the end of a line.
Zero or More * * * Matches zero or more occurrences of the preceding element.
One or More + \+ (Requires Backslash) + (Native) Matches one or more occurrences of the preceding element.
Zero or One ? \? (Requires Backslash) ? (Native) Matches zero or one occurrence (makes preceding element optional).
Interval Count {n,m} \{n,m\} (Requires Backslash) {n,m} (Native) Matches between n n n and m m m occurrences of the preceding element.
Alternation (OR) | \| (Requires Backslash) | (Native) Matches either the expression to its left OR to its right.
Grouping ( ) \( \) (Requires Backslash) ( ) (Native) Groups sub-expressions for quantifiers or capture boundaries.
⚠️ LPIC-1 Trap — The Escaping Inversion:
In BRE ( grep ): + , ? , { } , ( ) , and | are treated as literal characters unless escaped with a backslash ( \+ , \? , \{ \} , \( \) , \| ).
In ERE ( grep -E / egrep ): + , ? , { } , ( ) , and | are metacharacters by default. Escaping them ( \+ ) forces literal matching!
- 2. Anchors, Wildcards & Character Classes
- Positional Anchors
^ (Caret): Anchors match to the beginning of the line. ^root matches lines starting with root .
$ (Dollar): Anchors match to the end of the line. bash$ matches lines ending with bash .
^$ : Matches lines with zero characters between start and end ( empty/blank lines ).
^root$ : Matches lines containing only the exact string root and nothing else.
Bracket Expressions (Character Sets)
Bracket expressions define character sets matching any single character contained within the brackets:
[abc] : Matches either a , b , or c .
[a-z] : Matches any lowercase alphabetic letter.
[0-9] : Matches any numeric digit.
[^abc] : Negation (Inverted Set) — Matches any single character except a , b , or c when ^ is the first character inside the brackets.
POSIX Character Classes
POSIX defines locale-aware character class aliases that must be enclosed inside an outer set of brackets ( [[:class:]] ):
- POSIX Class Equivalent Set Matches
- [[:alnum:]] [a-zA-Z0-9] Alphanumeric characters (letters and digits)
- [[:alpha:]] [a-zA-Z] Alphabetic letters
- [[:digit:]] [0-9] Numeric digits
- [[:lower:]] [a-z] Lowercase alphabetic letters
- [[:upper:]] [a-Z] Uppercase alphabetic letters
- [[:space:]] [ \t\n\r\f] Whitespace characters (space, tab, newline, form feed)
- [[:blank:]] [ \t] Horizontal blank space (space and tab only)
- [[:punct:]] [!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~] Punctuation and symbol characters
[[:xdigit:]] [0-9a-fA-F] Hexadecimal digits # Match any line containing a 3-digit number:
- $ grep '[[:digit:]][[:digit:]][[:digit:]]' /var/log/syslog
- 3. The grep Family & Command-Line Flags
The GNU grep suite contains three command variants:
grep : Searches files using standard POSIX Basic Regular Expressions (BRE).
egrep (or grep -E ) : Searches files using Extended Regular Expressions (ERE).
fgrep (or grep -F ) : Searches for Fixed literal strings . It disables all regex parsing, making it extremely fast when searching for exact strings containing dots, brackets, asterisks, or dollar signs.
Essential grep Command-Line Flags
Flag Long Option Operational Behavior
-i --ignore-case Ignores case distinctions in both pattern and input data.
-v --invert-match Inverts selection: outputs only lines that do NOT match the pattern.
-c --count Suppresses normal output; prints only the numeric count of matching lines.
-l --files-with-matches Prints only the names of files containing matches (stops after first match).
-L --files-without-match Prints only the names of files that do NOT contain matches.
-n --line-number Prefixes each output line with its 1-based line number within the file.
-r / -R --recursive Recursively searches all directories ( -R follows symlinks).
-w --word-regexp Matches only whole words bounded by non-word characters.
-x --line-regexp Matches only whole lines (pattern must match the entire line from start to end).
-o --only-matching Prints only the exact matching segment of a line rather than the whole line.
-E --extended-regexp Interprets pattern as Extended Regular Expression (ERE, equivalent to egrep ).
-F --fixed-strings Interprets pattern as literal text (Fixed strings, equivalent to fgrep ).
-A <N> --after-context=<N> Prints <N> lines of trailing context after each match.
-B <N> --before-context=<N> Prints <N> lines of leading context before each match.
-C <N> --context=<N> Prints <N> lines of output context both before and after each match.
- 4. Practical Configuration & Log Filtering Recipes
- Recipe 1: Stripping Comments and Blank Lines from Config Files
A quintessential system administration task tested on LPIC-1 is inspecting active configuration parameters while filtering out comment lines (starting with # ) and empty lines: # Method 1: Chaining standard grep commands:
$ grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'
# Method 2: Single command using Extended Regular Expressions (ERE):
$ grep -Ev '^(#|$)' /etc/ssh/sshd_config
# Method 3: Handling leading whitespace before comment markers:
$ grep -Ev '^[[:space:]]*(#|$)' /etc/ssh/sshd_config Input File (/etc/ssh/sshd_config): Filtered Output (`grep -Ev '^(#|$)'`):
- ┌───────────────────────────────────┐ ┌───────────────────────────────────┐
- │ # OpenSSH Daemon Config │ │ Port 22 │
- │ Port 22 │ │ PermitRootLogin no │
- │ │ │ PasswordAuthentication yes │
- │ # Security Settings │ └───────────────────────────────────┘
- │ PermitRootLogin no │
- │ PasswordAuthentication yes │
- └───────────────────────────────────┘
Recipe 2: Matching IP Addresses with ERE # Find IPv4 addresses in access logs using ERE interval quantifiers:
$ grep -E '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/nginx/access.log
Recipe 3: Fast Fixed-String Search with fgrep # Search for literal string '$USER[0]' without escaping metacharacters:
$ fgrep '$USER[0]' /opt/scripts/*.sh
# Or using grep -F:
$ grep -F '$USER[0]' /opt/scripts/*.sh
💡 LPIC-1 Exam Fill-in-the-Blank Alert: What grep command option enables Extended Regular Expression (ERE) pattern interpretation? Answer: -E (or --extended-regexp )