Skip to content

Instantly share code, notes, and snippets.

@jagland
Last active June 22, 2023 10:01
Show Gist options
  • Save jagland/66507d585fd0bdefeb0f87cf39260c2d to your computer and use it in GitHub Desktop.
Save jagland/66507d585fd0bdefeb0f87cf39260c2d to your computer and use it in GitHub Desktop.
range-expander.sh
#!/bin/bash
# range-expander.sh, expands a range of ports/numbers e.g. VLANs, or Port/Interface numbers to a long list.
# intention is to plug into Ansible roles, but likely more to-do./
# Note, this will only sequence or expand the last numbers so "1/1/1-1/2/24" will work, but
# other combintations will only yield the start and ending left most parts e.g. "1/1/1-1/3/24" will not give
# any of "1/2/x".
# Please split that to "1/1/1-1/1/24,1/2/1-1/3/24" etc..
# Example usage
# ./range-expander.sh "1,2,3,1-1,9-17,1002"
# ./range-expander.sh "1/1/1-1/1/7"
# ./range-expander.sh "Fa0/1-Fa0/24"
INPUT=$1
temp=$(mktemp)
rangecheck() {
if [[ $1 =~ '-' ]] && [[ $1 != */* ]] ; then
IFS='-'
read -a range <<< "$1"
seq ${range[0]} ${range[1]} >> $temp
fi
}
slashcheck() {
if [[ $1 =~ "/" ]] && [[ $1 =~ '-' ]]; then
IFS='-'
read -a range <<< "$1"
lower=${range[0]##*/}
upper=${range[1]##*/}
leftlower=${range[0]%/*}
leftupper=${range[1]%/*}
sequence=$(seq -s, $lower $upper)
for ((i=$lower; i<=$upper; i++))
do
echo "$leftlower/$i" >> $temp
echo "$leftupper/$i" >> $temp
done
fi
}
singlevalue() {
if [[ ! $1 =~ "-" ]]; then
echo $1 >> $temp;
fi
}
for j in $(echo $INPUT | tr ',' ' ' | xargs)
do
slashcheck "$j"
rangecheck "$j"
singlevalue "$j"
done
sort -n $temp | uniq
rm $temp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment