In our previous post we saw how to use Basic regular expression along with grep to search for words and played across different basic regular expressions. In this post we will see how to use extended regular expressions to increase the power of grep command even better than Basic regular expression.
Extended regular expressions:
+ --Match one or more occurrences of previous character.
| -- Match Either character
? – Match 0 or 1 occurrence of previous character.
() –match a group of characters
{number} –Match number of occurrence of a character
{1, 3} –Match a character which is 1 to 3 times repetition
{5, } –Match a repeated character which is repeated 5 or more times.
Note1: In order to use this extended regular expressions we have to use –E option give grep the capability to understand Extended regular expressions.
Note2: egrep is nothing but grep –E, so try to avoid it if grep itself can do the work for you. Why to learn new command?
Examples:
Example1:Search for a words which contains one or more occurrence of ‘b’ between a and c.
grep –E ‘ab+c’ filename
Example2: Search for a word which contains zero or one occurrence of b between a and c
grep –E ‘ab?c’ filename
Example3: Search for a word which contains either a or b, a and b between d, e characters
grep –E ‘da|be’ filename
Example4: Search for a word which contains either a or b, but not both a and b between d, e characters
grep –E ‘d(a|b)e’ filename
Example5: Search for a word which contains only 2 ‘b’ between a and c character
grep –E ‘ab{2}c’ filename
Example6: Search for a word which contains 3 to 4 ‘b’ between a and c character
grep –E ‘ab{2,4}c’ filename
Example7: Search for a word which contains 3 or more ‘b’ between a and c character
grep –E ‘ab{3, }c’ filename
Note: When we are using {} we have to give a range, but in this example we did not give range we just started the range but did not end the range which indicates infinity.
Please share your thoughts on this.
SED(Steam EDitor ) Explained in detail for Linux/Unix | The Linux Juggernaut
[...] Note:As mention earlier to know more about this you have to learn RegExp using grep here and here. [...]