Home > Software engineering >  Grep only first octect of a subnet
Grep only first octect of a subnet

Time:06-20

I have a list of subnets in a file for eg:

2.1.1.0/24
2.2.2.0/24
21.2.2.0/24
24.5.7.0/24
22.6.7.0/24
224.25.75.0/24

How can I grep and get the output only of the subnet having first octet 2. The desired output should be

2.1.1.0/24
2.2.2.0/24

I tried to use cat file | grep '^2' but still I couldnt get the output as above. I get the whole file back.

CodePudding user response:

You need to make sure you match the first octet as a whole, not a part of it.

Since octets are separated with dots, you need to match a dot after 2.

You may use either \. or [.] to match a literal dot in the regex pattern:

grep '^2[.]' file

See the online demo:

#!/bin/bash
s='2.1.1.0/24
2.2.2.0/24
21.2.2.0/24
24.5.7.0/24
22.6.7.0/24
224.25.75.0/24'
grep '^2[.]' <<< "$s"

Output:

2.1.1.0/24
2.2.2.0/24

CodePudding user response:

Using grep

$ grep '^2\>' input_file
2.1.1.0/24
2.2.2.0/24
  • Related