Solti Solti - 6 months ago 14
Bash Question

Parsing 1:2:10 string into 3 variables

In bash shell, what is the best way to parse input string 1:2:10 to set A=1, B=2, C=10 ? Automatically set A, B, C to the 3 numbers separated by ':'.

In addition, if the input only has 1:10, set A=1, C=10, and then B = some default value.

Yes, I'm trying to simulate the format used in Matlab. 1:2:10 is expanded to 1, 3, 5, 7, 9 and 1:10 is expanded to 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. I'm thinking if I can get A, B, and C set right, it's easy to do this behavior.

Thanks!!

Answer
$ IFS=: read a b c <<< '1:2:10'
$ echo $a
1
$ echo $b
2
$ echo $c
10
$ seq "$a" "$b" "$c"
1
3
5
7
9
$ IFS=: read a b c <<< '1:10'
$ echo $c

$ [ "$c" ] || seq "$a" "$b"
1
2
3
4
5
6
7
8
9
10