Skip to main content
1 of 5
AdminBee
  • 23.6k
  • 25
  • 55
  • 77

If I understand you correctly, you want to find all IPs from a given file that fall into the same network as a given "reference" network base IP, where you want to configure the netmask according to the CIDR network classes.

In that case, the following awk program should work:

awk -v cl=2 -v nw="8.6.0.0" -F'.' 'BEGIN{split(nw,ref,/\./)} NF==4{for (i=1;i<=cl;i++) {if ($i!=ref[i]) next} print}' ips.txt
  • You specify the "network class" numerically as awk variable cl, and the reference base IP as awk variable nw via -v statements on the command line. A network of /16 would be specified as cl=2, a network of /24 as cl=3.
  • The program will use the . as field separator.
  • In the beginning, the reference IP is split by fields into an array ref.
  • For each line encountered, the program first checks if it contains 4 fields (minimum sanity check for an IP). If so, it compares the first cl fields of both the current line and the reference IP. If any of them doesn't match, the line is skipped and processing proceeds to the next line. If all relevant fields matched, the line is printed.
AdminBee
  • 23.6k
  • 25
  • 55
  • 77