Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted

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
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.