Skip to main content

How to read and parse user input specified as a list or a range of numbers [Resolved]

What is the easiest way to allow user to enter numbers in following formats so that each individual number can be printed.

comma separated ( 1,5,7 ), space separated ( 1 5 7 ) and range separated ( 1-3,5)

Expected output if input is comma separated: 
1
5
7
Expected output if input is space separated: 
1
5
7
Expected output if input is - and , separated:
1
2
3
5

I have tried following ways, defining logic only

input_string="1,5,7"
IFS=' ' read -r -a array <<< "$input_string"
echo ${array[1]} etc..

input_string="1 5 7"
 read -r -a array <<< "$input_string"
echo ${array[1]} etc..

Wondering how to handle - and , both together in array , thanks


Question Credit: Bharat
Question Reference
Asked August 20, 2018
Tags: bash
Posted Under: Unix Linux
18 views
2 Answers

Try also

T="$@"
echo {1..100} | { cut -d" " -f"${T// /,}"; }

credit: RudiC
Answered August 20, 2018
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA