"grep: Unmatched [" error when using regex
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
put backslash before the last bracket in the line (which is unmatched) [ is a special character in regex for classes.
So you want:
tail -n 100000 gateway.log | grep -B10 -A10 'Nov 22 [0-9]:[0-9]:[0-9] Received Packet from \[10.50.98.68'
Also like the other answer says, you have other issues with your regex, like periods that you want to be literal, and the fact that you only allow for one number between each colon which will fail on some times of day. For the time you want [0-9]\{1,2\}:[0-9]\{1,2\}:[0-9]\{1,2\}
and for the IP address, if you want a regex that will match any valid IP address onfly, its more complicated than you think. You didnt say if the IP will change or not.