I have an input file with IPv4 addresses: - - - - - -

How I can convert the address ranges to netmasks? The result should be:
  • 3
    Several of the results you ask for are incorrect, so no valid bash script will produce them. For instance, the first range is not expressible using a netmask: gives -, and the next wider gives - Also, ranges ending in .0 cannot be produced by any netmask. – zwets Jan 31 '17 at 9:28
  • @Zanna you're cheating, the poster asked using bash. My bash has no ipcalc builtin. ;-) – zwets Jan 31 '17 at 9:52
  • @zwets ah I've figured it out! But you're right, the shell needs a lot of help hahaha – Zanna Jan 31 '17 at 10:00

First you will need to install a package to do the conversion

sudo apt install ipcalc

Now you can do it with this little script (please note that it doesn't work if you quote the variable):

$ while read line; do if [[ $line = *-* ]]; then (ipcalc $line | sed '2!d'); else echo $line; fi; done < file

or more readably

while read line; do
   if [[ $line = *-* ]]; then 
     (ipcalc $line | sed '2!d')
   else echo $line
done < file
  • @Oleksii always a pleasure :) – Zanna Feb 3 '17 at 8:19

Perhaps not surprisingly, there is a CPAN perl module Net::CIDR for this.

So for example:

$ perl -MNet::CIDR=range2cidr -lne 'print for range2cidr $_' yourfile

The module is available on Ubuntu by installing the libnet-cidr-perl package.

NB I have not validated your input or the results.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.