Regex for Linux, regular expressions are similar to the wildcards which allow us to create a pattern to perform a specific search in data. Regular expressions are lot more powerful and also known as “regex” or “regexp“.
The commands in Linux that are commonly used with regex are tr
, sed
, vi
and grep
.
Basic Regular Expressions
Here are listed some of the basic regular expressions used on Linux.
Expression | Description |
---|---|
^ | Matches the beginning of the string |
$ | Matches the end of the string |
. | Matches any single character except “n“ |
* | Matches up zero or more times the preceding character |
\ | Preserve the meaning of the character by escaping it |
() | Group the characters |
? | Match one character |
Examples
To search a file with a specific letter you can use the following command.
grep a content.txt
This command searches for the occurrence of “a” in the content.txt
file and outputs it.
To search for a line that starts with a specific character or word you can use this “^” expression.
grep ^d content.txt
This command outputs all lines that is starting with “d”.
To search for a line that ends with a specific character or word you can use this “$” expression.
grep g$ content.txt
This command outputs all lines that is ending with “g”.
To search for empty line you can use the following command.
grep '^$' content.txt
Interval Regular Expressions
The interval regular expressions are used to match the number of times the characters appear in a string.
Expression | Description |
---|---|
{n} | Matches the character appearing “n” number of times. |
{n,m} | Matches the character appearing “n” number of times but not more than “m“ |
{n,} | Matches only if there are more than “n” number of characters |
Example
grep -E n{2} content.txt
This command outputs the line that contains 2 occurrences of “n”.
Output
Running
Extended Regular Expressions
Extended regular expressions are combination of two or more expressions as listed below.
Expression | Description |
---|---|
\+ | Match one or more occurrences of the previous character. |
\? | Matches zero or one occurrence of the previous character. |
Example
To filter out lines where character ‘o’ precedes character ‘m’ you can use this kind of expression.
grep "o\+m" content.txt
This command outputs something like this.
Output
Zombies
These are some of the common regular expressions used in Linux.
Prepare yourself for a role working as an Information Technology Professional with Linux operating system
Conclusion
Now you have learned how to create a regular expression for Linux.
Thanks for your time. If you face any problem or any feedback, please leave a comment below.