Reputation: 1328
I have time stamp entry in a log file in 2nd column in format HH:MM:SS:mmm
eg snippet
15-01-2017 21:15:10:266
15-01-2017 21:15:10:389
15-01-2017 21:15:15:266
15-01-2017 21:15:12:124
15-01-2017 21:15:12:266
15-01-2017 21:15:15:266
15-01-2017 21:15:20:266
I am trying
awk '$2 == "21:15:[0-9]{2}:[0-9]{3}"'
to match all the entries at 21:15 but this doesn't seem to be working. Why isn't it working? How can I make it work?
Upvotes: 1
Views: 4963
Reputation: 289645
You are using $2 == regexp
. But to check regexps in awk
you need to use ~
, otherwise ==
is checking the string literally:
awk '$2 ~ /^21:15:[0-9]{2}:[0-9]{3}/' file
This returns:
15-01-2017 21:15:10:266
15-01-2017 21:15:10:389
15-01-2017 21:15:15:266
15-01-2017 21:15:12:124
15-01-2017 21:15:12:266
15-01-2017 21:15:15:266
15-01-2017 21:15:20:266
From the GNU awk user's guide on 3.1 How to Use Regular Expressions:
Regular expressions can also be used in matching expressions. These expressions allow you to specify the string to match against; it need not be the entire current input record. The two operators ‘~’ and ‘!~’ perform regular expression comparisons. Expressions using these operators can be used as patterns, or in if, while, for, and do statements. (See Statements.) For example, the following is true if the expression exp (taken as a string) matches regexp:
exp ~ /regexp/
Also from 6.3.2.2 Comparison Operators:
String comparisons and regular expression comparisons are very different. For example:
x == "foo"
has the value one, or is true if the variable x is precisely ‘foo’. By contrast:
x ~ /foo/
has the value one if x contains ‘foo’, such as "Oh, what a fool am I!".
Upvotes: 1