0

I'm scratching my head on the following oversimplistic grep command:

grep "GMT \+[0-9]{2}:[0-9]{2}" gmt_funny.txt

where gmt_funny.txt contains:

2012-09-01 00:00:16.825 (GMT +02:00)

I've just discovered that the grep command doesn't match the line, unless I specify -E as follows:

grep -E "GMT \+[0-9]{2}:[0-9]{2}" gmt_funny.txt

Does this means grep doesn't handle extended regular expressions ? The man grep seems to indicate that { and } is not supported, shall be replaced by \{ and \}. Is this correct?

If yes, is there an explanation to this misleading particular behaviour of grep?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
SCO
  • 1,832
  • 1
  • 24
  • 45
  • 6
    Normally, grep uses BRE, you need flag to access ERE. More info: http://en.wikipedia.org/wiki/Regular_expression#POSIX `\{` and `\}` are BRE syntax, while `{` and `}` are ERE syntax. – nhahtdh Feb 26 '13 at 10:41
  • Also, assuming ERE, your regex expects a literal `+` where there isn't one. – Tim Pietzcker Feb 26 '13 at 10:42
  • 1
    Instead of scratching your head, learn about `man`. `man grep` could've told you. – Ingo Feb 26 '13 at 10:46
  • @nhahtdh Would you mind submitting this as an answer please ? ;) – SCO Mar 19 '18 at 16:26
  • 1
    For the "why" part, perhaps see e.g. https://stackoverflow.com/a/39367415/874188 – tripleee Dec 04 '18 at 04:38

1 Answers1

1

By default, grep uses BRE syntax, where quantifier syntax \{m,n\} requires backslash \ on the curly brackets. So your first command can be changed to:

grep "GMT \+[0-9]\{2\}:[0-9]\{2\}" gmt_funny.txt

To use the ERE syntax in grep, where quantifier syntax is the familiar {m,n}, you need to specify -E flag in your command, as you have found out in the question.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162