sh-4.3$ grep "hi +hello"
sh-4.3$ grep "hi +hello" test
sh-4.3$ grep "hi \+hello" test
hi hello
hi hello
sh-4.3$ grep "hi *hello" test
hi hello
hihello
hi hello
sh-4.3$In the above code, escape character is required with '+' regex character, but while using '*' regex character escape character is not required.
Can anyone explain the reason for that?
1 Answer
Standard GNU grep recognises BRE (basic regular expressions) and * is an original metacharacter in BRE while + is an extension to BRE. For + to be recognised as a metacharacter in BRE, it must be escaped. However, if you tell grep to use ERE (extended regular expressions) by using the -E flag, you do not need to escape any metacharacter (if you escape them, they will become literals instead). There's a bit of explanation in the grep manual and here's a more detailed overview
$ grep -E 'hi +hello' test
hi hello
hi helloYou can also use egrep
$ egrep 'hi +hello' test
hi hello
hi helloI decide whether to use BRE or ERE based on the total number of backslashes I will have to type...
4