“grep: Unmatched [” error when using regex

grepquotingregular expression

I'm trying to find a pattern similar to this:

tail -n 100000 gateway.log | grep -B10 -A10 'Nov 22 11:13:56 Received Packet from [10.50.98.68'

Where "11:13:56" could be any time.

This is what I came up with:

tail -n 100000 gateway.log | grep -B10 -A10 'Nov 22 [0-9]:[0-9]:[0-9] Received Packet from [10.50.98.68'

I'm not sure what it is referring to when it says "unmatched [". This part "[0-9]:[0-9]:[0-9]" is supposed to be regex. This part "[10.50.98.68" is supposed to be a string.

Best Answer

In a grep regular expression, [ is a special character. For a literal [, you need to backslash escape it, like so: \[.

Note that the entirety of Nov 22 [0-9]: ... [10.50.98.68 is a regular expression. You can't just point to it and say "this part is a regex, this part should be a literal string" and expect grep to be able to read your thoughts. That's why you need to escape any special characters that are part of literal strings you want to match.


Unrelated, but each occurrence of [0-9] in your regular expression only matches a single character. Also, . is a special character that will need to be escaped as well. You probably want something like the following for your regular expression:

^Nov 22 [0-9][0-9]:[0-9][0-9]:[0-9][0-9] Received Packet from \[10\.50\.98\.68
Related Question