Linux Regular Expressions (Regex) are special characters that help search data based on matching complex patterns. They are used in many Linux command-line utilities, such as rename, bash, sed, grep, etc. In this guide, we’ll be focusing on the grep command.
grep Command Purpose and Syntax
grep searches for patterns in a file(s). patterns refer to one or more patterns separated by newline characters, and grep prints each line that matches a defined pattern.
# grep [operators...] patterns [file...]
Types of Regular Expressions
There are three main types of Linux regular expressions:
Basic Regular Expressions
A Basic Regular Expression (BRE) is a regular expression consisting of the exact characters of the string to be matched.
Basic Regular Expression Operators
- . — replaces any character
- ^ — matches start of string
- $ — matches end of string
- * — matches up zero or more times the preceding character
- — represent special characters
- () — groups regular expressions
- ? — matches up exactly one character
Basic Regular Expression – Example
In this example, we list all comments in the /etc/adduser.conf file. (Note that the # sign prefaces comments in .conf files).
# grep ^# /etc/adduser.conf
Display all comments (#) in /etc/adduser.conf.
Interval Regular Expressions
An Interval Regular Expression (IRE) is a regular expression that reports the number of characters in a string.
Interval Regular Expression Operators
- {n} — matches the preceding character appearing ‘n’ times exactly
- {n,m} — matches the preceding character appearing ‘n’ times but not more than m
- {n, } — matches the preceding character only when it appears ‘n’ times or more
Interval Regular Expression – Example
In this example, we’ll find all content in the /etc/adduser.conf that contains the ‘l‘ character exactly two times consecutively.
# grep -E l{2} /etc/adduser.conf
Extended Regular Expressions
An Extended Regular Expression (ERE) is a regular expression that contains more than one expression.
Extended Regular Expressions Operators
The extended regular expression contains more than one expression.
- + — matches one or more occurrences of the previous character
- ? — matches zero or one occurrence of the previous character
Extended Regular Expression – Example
In this example, we’ll search /etc/adduser.conf where character ‘t‘ precedes character ‘a.’
# grep "t+a" /etc/adduser.con