SBC
SBC

Reputation: 131

how to grep range of numbers

in a text file I have the following entries:

10.1.0.10-15
10.1.0.20-25
10.1.0.30-35
10.1.0.40-45

I would like to print 10.1.0.10,15, 20, 25,30

cat file | grep 10.1.0.[1,2,3][0.5] -- prints 10,15,20,25,30, 35.

How do I suppress 35?

I do not want to use grep -v .35 ...just want to print specific IPs or #s.

Upvotes: 0

Views: 8725

Answers (3)

anubhava
anubhava

Reputation: 784998

You can use:

grep -E '10\.1\.0\.([12][05]|30)' file

However awk will be more readable:

awk -F '[.-]' '$4%5 == 0 && $4 >= 10 && $4 <= 30' file
10.1.0.10-15
10.1.0.20-25
10.1.0.30-35

Upvotes: 2

elcortegano
elcortegano

Reputation: 2684

I'm not sure if what you want is just printing the first two IPs, excluding that one with 35. In that case cat file | grep '10.1.0.[1-3]0.[15|25]' does the job.

Remember that you can use conditional expressions such as | to help you.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 753555

Note that the , and . in the character classes are not needed — in fact, they match data that you don't want the pattern to match. Also, the . outside the character classes match any character (digit, letter, or . as you intend) — you need to escape them with a backslash so that they only match an actual ..

Also, you are making Useless Use of cat (UUoC) errors; grep can perfectly well read from a file.

As to what to do, probably use:

grep -E '10\.1\.0\.([12][05]|30)' file

This uses the extended regular expressions (formerly for egrep, now grep -E). It also avoids the dots from matching any character.

Upvotes: 1

Related Questions