-3

Having a list of CIDR ranges in a file. Some of them are not "well formed" in case of they are valid but some programs won't accept them.

Example: 192.168/24

Resolves to: 192.168.0.0/24

So, in this case it should be checked if there are 4 octets. If not, the script should apply .0 for each missing one.

1.1.1/24 becomes 1.1.1.0/24

2.2/16 becomes 2.2.0.0/16 ...

Thanks :-)

1 Answers1

0

The trick is

  1. Split the (partial) address into an array
  2. Append 4 zeros to the end of the array
  3. Take the first 4 elements of the resulting array and rejoin with .

For example:

cidr=192.168/24
IFS=. read -a octets <<< "${cidr%/*}"
octets+=(0 0 0 0)
printf -v network "%d.%d.%d.%d" "${octets[@]:0:4}"
printf '%s/%d\n' "$network" "${cidr#*/}"

Otherwise,

chepner
  • 497,756
  • 71
  • 530
  • 681