zaydek zaydek - 4 months ago 9
Bash Question

Generate case range in bash

I want to input two and three digit numbers into a function and output a case range, i.e., input

33
and
66
and output
3[3-9] | [4-5][0-9] | 6[0-6]
or input
33
and
666
and output
3[3-9] | [4-9][0-9] | [1-5][0-9][0-9] | 6[0-5][0-9] | 66[0-6]


What are some ideas as to how? Thanks!

Answer

Just want to share the final code: https://gist.github.com/zaydek/1627329f88c444f6d71d5cbc0cda616f :)

function enc {

    a=${1: -3:1}; b=${1: -2:1}; c=${1: -1}
    d=${2: -3:1}; e=${2: -2:1}; f=${2: -1}

    if   (( $[a] < $[d] )); then

        if   (( $b$c == 00 && $e$f == 99 )); then echo [$a-$d][0-9][0-9]
        elif (( $b$c == 00 )); then if (( $[a+1] < $d )); then echo [$a-$[d-1]][0-9][0-9] "|"; echo $(enc $[d]00 $d$e$f)
                                                          else echo $a[0-9][0-9] "|"; echo $(enc $[a+1]00 $d$e$f); fi

        else echo $(enc $a$b$c $[a]99) "|"; echo $(enc $[a+1]00 $d$e$f); fi

    elif (( $b < $e )); then

        if   (( $c == 0 && $f == 9 )); then echo $a[$b-$e][0-9]
        elif (( $c == 0 )); then if (( $[b+1] < $e )); then echo $a[$b-$[e-1]][0-9] "|"; echo $(enc $a$[e]0 $d$e$f)
                                                       else echo $a$b[0-9] "|"; echo $(enc $a$[e]0 $d$e$f); fi

        else echo $(enc $a$b$c $a$[b]9) "|"; echo $(enc $a$[b+1]0 $d$e$f); fi

    else

        if (( $c == $f )); then echo $a$b$c
        else echo $a$b[$c-$f]; fi; fi

}

function int {

    if [[ $1 = *.* ]]; then

        integer=${1%.*}
        decimal=${1#*.}

        if (( ${decimal:0:1} >= 5 )); then integer=$[integer+1]; fi

         echo $integer
    else echo $1; fi

}

function cse {

    minimum=$(int $(echo $1 $2 | awk '{ print ($1/$2)*( 90) }'))
    maximum=$(int $(echo $1 $2 | awk '{ print ($1/$2)*(110) }'))

    echo $(enc $minimum $maximum)

}

cse $1 $2

cse takes two inputs, converts them to decimals, and multiples each from a range, i.e., 90 and 110 for -10% and +10% error range, then passes off the minimum and maximum outputs as inputs to enc which is a recursive function that generates case range syntax (with syntax optimization).

Please note, bash does not appear to handle expressions for case ranges as expected or intended. Though, this code can be used to generate case ranges for all 2 to 3 digit numbers and then copied and pasted as inline code.