Soncire
Soncire

Reputation: 309

How to match a specific number range with a regex using grep only

For example I have a time range below:

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

And what I want is to get the numbers from 13 to 20 only using grep -E '[1-2][??]' is it possible?

please dont give answer about awk I'm not asking about it thank you very much

Upvotes: 4

Views: 35643

Answers (3)

Bohemian
Bohemian

Reputation: 425033

This should do it:

^(1[3-9]|20)$

Upvotes: 5

Yeasir Arafat Majumder
Yeasir Arafat Majumder

Reputation: 1264

You need to enclose the regular expression inside double quotes(" "). Besides, considering a broader search domain, if the numbers are more than 2 digits, you need to put additional quantifiers in the expression. Say you want to search for numbers in the range

1865259000 to 1865361999

your regular expression should be:

"1865259[0-9]{3}|18652[6-9][0-9]{4}|18653[0-6][0-1][0-9]{3}"

the number inside curly braces means the pattern should match exactly that number of times. so,

 [0-9]{2}

means 2 occurrences of digits between 0 to 9.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

| means alternation in regular expressions. You can think of this like a logical or. Thus:

1[3-9]|20

means

1 followed by 3, 4, 5, 6, 7, 8, or 9, OR 2 followed by 0

This will match any of the numbers indicated (13, 14, 15, 16, 17, 18, 19, or 20).

The above could be 1[1-9]|2[0-6] which would be:

1 followed by 1 through 9 OR 2 followed by 0 through 6

as Bohemian indicates. The ^ and $ zero width assertion anchors mean "start of the string" and "end of the string" respectively. Their exact meaning can vary depending on the regex flavor, but in egrep and other line-based regex flavors that is what they mean. You would want to use these if there is the possibility of other characters in the line as in

a13b
&20-

If you know that the number will be all that is on that particular line, they are not strictly necessary.

Upvotes: 5

Related Questions