How to find the count of IP addresses that belong to different subnets and display the count?

Hi,

I have a file with a list of bunch of IP addresses from different VLAN's . I am trying to find the list the number of each vlan occurence in the output
Here is how my file looks like

1.1.1.1
1.1.1.2
1.1.1.3

1.1.2.1
1.1.2.2

1.1.3.1
1.1.3.2
1.1.3.3
1.1.3.4

So what I am trying to get out of this is to using grep and count mechanism to spit something like this

1.1.1.x  occrences 3
1.1.2.x  occrences 2
1.1.3.x  occrences 4

Using awk :-

awk '
        NF {
                SN = $0
                sub(/\.[^.]*$/,X,SN)
                ++A[SN]
        }
        END {
                for ( k in A )
                        print k ".X", "Occurrences:", A[k]
        }
' file

If you have them in a file, how about:-

cut -f-3 -d"." input|sort|uniq -c

Would that do? It's not quite the pretty output, but you get the detail you need.

I hope that this helps,
Robin

2 Likes

Adding 1 more solution which may help future users.

awk '
match($0,/[0-9]+\.[0-9]+\.[0-9]+/){
  array[substr($0,RSTART,RLENGTH)]++
}
END{
  for(i in array){
    print i" occrences "array[i]
  }
}'  Input_file

Love "auto bumping" functionality :slight_smile:

Thanks,
R. Singh

1 Like