-4

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?

0

3 Answers 3

0

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,
1
  • hi, this answer almost works. but it fails if i give an input like so host[9-10],host15,host[23-32] it has something to do with regex handing single count host with double digits. i assume triple digits would also fail. I am trying to work it out. But i am pretty weak in regex. This part of the script is just for user experience so one doesnt have to input a hostlist from host1,host2,host9,....host128. Commented Mar 30, 2020 at 19:29
-1

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
3
  • Be careful using 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 30, 2020 at 7:18
  • @ctrl-alt-delor: I'm well aware of the 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.
    – RudiC
    Commented Mar 30, 2020 at 8:02
  • @RidiC The warning is not for you. It if for all those that come after us. Commented Mar 30, 2020 at 14:21
-1

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
2
  • 1
    Be careful using 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
  • Yes, sanitize that input before use! Wash your hands 20 seconds also.
    – Larry
    Commented Mar 30, 2020 at 0:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .