User will provide a list containing ranges. I need to convert it to a list of discrete values.
For example
Input
host[1-5],host7,host[13-15]
Output
host1,host2,host3,host4,host5,host7,host13,host14,host15.
How can I achieve this result?
Try this:
hosts=($(echo "host[1-5],host7,host[13-15]" | sed 's/,/ /g'))
string=""
for h in ${hosts[@]}; do
if [[ ! ${h//[^0-9]/} =~ ^[0-9]$ ]]; then
for i in $(seq ${h//[^0-9]/ }); do
string+="${h%[*}$i,"
done
else
string+="$h,"
fi
done
echo "${string%,}"
Output:
host1,host2,host3,host4,host5,host7,host13,host14,host15,
Try bash
's "Parameter expansion / pattern substitution"
$ hostlist=host[1-5],host7,host[13-15]
$ H1=${hostlist//[/{}
$ H2=${H1//]/\}}
$ H3=${H2//,/ }
$ H4=$(eval echo ${H3//-/..})
$ H5=${H4// /,}
$ echo "$H5"
host1,host2,host3,host4,host5,host7,host13,host14,host15
eval
connotations. While I appreciate corrections / amendments and learn from those, I'd like to learn from you how eval echo
in a variable assignment can execute arbitrary instructions.
If you change your input to
hostlist=host{{1..5},7,{13..15}}
then
eval echo $hostlist | tr ' ' ,
host1,host2,host3,host4,host5,host7,host13,host14,host15
eval
: It can result in you executing arbitrary instructions. The provider of the data can do what ever they want to your account.
Commented
Mar 29, 2020 at 21:54