Linux grep Regular Expressions
The grep tool has the following options to use regular expressions:
- -E : String is read as ERE (Extended Regular Expressions)
- -G : String is read as BRE (Basic Regular Expressions)
- -P : String is read as PRCE (Perl Regular Expressions)
- -F : String is read literally.
Print Lines Matching A Pattern
The grep command will search for line that matches the specified pattern.
Syntax:
Example:
Look at the above snapshot, all the matching pattern lines are displayed and pattern is highlighted.
Concatenating Characters
If a pattern is of concatenating characters then it has to be matched as it is, for the line to be displayed.
Example:
Look at the above snapshot, lines matching exactly the specified patterns are displayed.
One Or The Other
Here pipe (|) symbol is used as OR to signify one or the other. All the three versions are shown. Options -E and -P syntax are same but -G syntax uses ().
Syntax:
Example:
Look at the above snapshot, either pattern ‘j’ or ‘g’ should be matched to display the lines.
One Or More / Zero Or More
The * signifies zero or more times occurence of a pattern and + signifies one or more times occurence.
Syntax:
Example:
Look at the above snapshot, * character displays zero or more times occurence of pattern ‘1’. But + character displays one or more times occurence.
Match The End Of A String
To match the end of a string we use $ sign.
Syntax:
Example:
Look at the above snapshot, lines are displayed matching the end of a string.
Match The Start Of A String
To match the start or beginning of a file we use caret sign (^).
Syntax:
Example:
Look at the above snapshot, lines are displayed matching the start or beginning of a string.
Separating Words
Syntax:
Example:
Look at the above snapshot, by giving command “grep some file all the lines matching to the word ‘some’ are displayed. But by giving command “grep ‘bsomeb’ file” only lines matching single word ‘some’ are displayed.
Note: This can also be done with the help of -w option.
Syntax:
Example:
Look at the above snapshot, command “grep -w some file” displays the same result as b character.