Linux Regular Expressions are special characters which help search data and matching complex patterns. Regular expressions are shortened as 'regexp' or 'regex'. They are used in many Linux programs like grep, bash, rename, sed, etc.
For ease of understanding let us learn the different types of Regex one by one.
Some of the commonly used commands with Regular expressions are tr, sed, vi and grep. Listed below are some of the basic Regex.
| Symbol | Descriptions |
|---|---|
| . | 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 |
Let's see an example.
Execute cat sample to see contents of an existing file
Search for content containing letter 'a'.
'^' matches the start of a string. Let's search for content that STARTS with a
Only lines that start with character are filtered. Lines which do not contain the character 'a' at the start are ignored.
Let's look into another example -
Select only those lines that end with t using $
These expressions tell us about the number of occurrences of a character in a string. They are
| Expression | Description |
|---|---|
| {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 |
Example:
Filter out all lines that contain character 'p'