#!/bin/bash debug=false #debug=true function Init { # constants cidr_input_file="./input.list" cidr_output_file="./output.list" default_maskvalue=24 # variables prev_first3="" prev_octet4="" prev_comment="" match_found=false prev_match_found=false prev_has_been_written=false current_maskvalue=0 active_maskvalue=0 exitcode=0 } function CondenseOnThreeOctets { $verbose && echo -n "["$(date)"] -- applying CIDR mask where possible ..." # delete and create a new output file rm -f "${cidr_output_file}" && touch "${cidr_output_file}" while read line ; do if [ ! -z "$line" ] ; then # ignore empty lines if [[ $line != \#* ]] ; then # ignore lines that begin with a # character # only take first word on each line as IP address current_ip=$( cut -f1 <<< "${line}" ) # take everything after /* as a comment but only if it exists [[ ${line} == */\** ]] && comment=$( sed 's|^.*/\*|/\*|' <<< "${line}" ) || comment="" while IFS=. read octet1 octet2 octet3 octet4 ; do $debug && echo first3="${octet1}.${octet2}.${octet3}" $debug && echo "-- now checking - IP entry: ${first3}.${octet4}" if [ -z "$prev_first3" ] ; then # first time through the loop - no previous values have been saved yet. SaveThisIpAsPrev else if [ "$first3" = "$prev_first3" ] ; then # if here then first 3 octets matched so we can combine this IP with the previous IP match_found=true SaveThisIpAsPrev else # if here then first3 octets are different so it's OK to save the previous IP match_found=false WriteIpAsCIDR fi fi done <<< "${current_ip}" fi fi done < "${cidr_input_file}" # write out last IP WriteIpAsCIDR $verbose && echo " done!" } function CalcMasks { [[ $active_maskvalue -eq 0 ]] && active_maskvalue=${default_maskvalue} if [[ $octet4 == *"0/"* ]] ; then current_maskvalue=${octet4:2} [[ $current_maskvalue -lt $active_maskvalue ]] && active_maskvalue=${current_maskvalue} else current_maskvalue=0 fi } function SaveThisIpAsPrev { $debug && echo "-- saving current IP as previous IP" CalcMasks prev_first3=$first3 prev_octet4=$octet4 prev_comment="$comment" prev_match_found=$match_found prev_has_been_written=false } function WriteIpAsCIDR { if [ ! -z "$prev_first3" ] ; then if ! $prev_has_been_written ; then if $prev_match_found ; then buildline="$prev_first3.0/$active_maskvalue\t$prev_comment" else buildline="$prev_first3.$prev_octet4\t$prev_comment" fi echo -e "${buildline}" >> "${cidr_output_file}" prev_has_been_written=true active_maskvalue=0 fi fi SaveThisIpAsPrev } echo "["$(date)"] >> started [$0@$HOSTNAME]" Init CondenseOnThreeOctets echo "["$(date)"] << finished [$0@$HOSTNAME]" exit $exitcode