Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Expand alphanumeric range from variable in bash

I have a variable which contains two alphanumeric sequences separated by a hyphen. I need to expand these to the full inclusive range separated by spaces. Here are some examples to illustrate:

0-9     -> 0 1 2 3 4 5 6 7 8 9
a-h     -> a b c d e f g h
B-Z     -> B C D E F G H I J K L M N O P Q R S T U V W X Y Z
95-101  -> 95 96 97 98 99 100 101

These match bash brace expansion format, so I was looking to use this e.g. {0..9}, but I can’t find a way to put variables in the expansion. I can get each side of the expansion, and using seq I can expand the numeric ones, but haven’t found a way to expand the alphabetic sequences.

Any solution is fine, whether it uses bash brace expansion, manually separates the sides and expands them through another function, or does anything else.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With ksh, can be run in a subshell in bash:

#!/bin/bash

x=0-9

read -ra digits < <(
    ksh -c '
        range=$1
        exp={$range}
        echo ${exp/-/..}
    ' ksh $x
)
printf '%s\n' "${digits[@]}"

0
1
2
3
4
5
6
7
8
9

Will work with alphabetic characters too.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading