user2607367
user2607367

Reputation: 225

Regular expressions in shell script

I am trying to search a line in a log file, based on the regular expression. When I use below command I am getting the proper output. Platform: Solaris, Shell: Bash

grep 14:[00-29]

O/P: Apr 02 14:07:35 [192.168.162.117.113.169]

But when I use the below command I am getting blank output

grep 14:[00-29]:[00-59].

Am I missing something?

Upvotes: 0

Views: 96

Answers (4)

anubhava
anubhava

Reputation: 785146

Both of these regex:

14:[00-29]

and

14:[00-29]:[00-59]

are incorrect and they aren't really matching values from 0 to 29 for example.

For range of 00 to 59 you can use:

\b(0[0-9]|[1-5][0-9])\b

And for the range of 0 to 29:

\b(0[0-9]|[12][0-9])\b

Upvotes: 0

fedorqui
fedorqui

Reputation: 289725

You need to use another regex. For example this makes it:

grep "14:[0-2][0-9]:[0-5][0-9]" file
          ^^^  ^^^   ^^^  ^^^
           |    |     |   any number
           |    |    from 0 to 5
 from 0 to 2   any number

See the output:

$ grep "14:[0-2][0-9]:[0-5][0-9]" file
Apr 02 14:07:35 [192.168.162.117.113.169] 

The first one was matching but casually:

$ grep 14:[00-29] file
Apr 02 14:07:35 [192.168.162.117.113.169]
          ^^
          | |
          | 7 is not matched
          [00-29] matches this 0

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295403

[00-29] matches only the characters 0, 1, 2 and 9.

[00-59] matches only the characters 0, 1, 2, 3, 4, 5 and 9.

The [] construct creates a character class, not a numeric range.

You might want grep -E 14:[0-2][0-9].

Upvotes: 1

Your regex is not doing what you think. What it is actually doing is saying get me 14:[ONE number that is 0, 0-2 or 9]:[ONE number that is 0, 0-5, or 9]. You should change it to 14:[0-9]|([0-2][0-9]):[0-9]|([0-5][0-9])

Upvotes: 1

Related Questions