bash getopts, intervalos de análise

0

Qual seria a melhor abordagem para analisar intervalos de valores de argumentos usando getopts ? Como exemplo:

$ script.sh -r2-4,6,8-10

No meu script, eu teria um array com os valores 2, 3, 4, 6, 8, 9 e 10.

    
por c0dem4gnetic 27.12.2012 / 11:02

1 resposta

1

Se você quer usar ambos -r ..., .. e -r ... -r ... -r ...: crie um script como este "toto.bash":

#!/usr/bin/bash

    add_ranges () #this will add each integers or ranges (a-b) into the array: myarray
    {
       #first we test that we only have those validchars (makes the second step below much easier to write)
       validchars='[1234567890,-]'
       echo "$@" | grep "${validchars}" >/dev/null && {
          : ; #only valid chars, probably ok. (but could be wrong, ex: 1-  2,, 4-3  etc...)
       } || {
          echo "The ranges you entered are not valid : they should only contain such characters: ${validchars}"
          exit 1 ;
       }
       #secondly we now try to handle the current ranges lists (comma separated)
       for range in $(echo "${@}" | tr ',' ' ')
       do
          if   [[ ${range} =~ ^[0-9]+$ ]]     # [[ can handle regexp matching, and doesn't need to quote parameters
          then
             myarray[${#myarray[*]}]=${range}  #add this after the latest element in myarray
          elif [[ ${range} =~ ^[0-9]+-[0-9]+$ ]]
          then
             newrange=$(echo "$range" | sed -e 's/-/../')
             for i in 'eval echo {$newrange}' # {a..b} means: all integers a to b
             do
                myarray[${#myarray[*]}]=${i}  #add this after the latest element in myarray
             done
          else
             echo "ERROR: I can not recognize this range: $range"
             exit 1
          fi
       done
    }

   ###### handle options using getopts:
   OPTIND=1; #here for compatibility's sake: in case you add another function that uses getopts, reminds you to re-set OPTIND each time.
   while getopts "r:" zeoption; do
      case $zeoption in
         r)
        allranges="${OPTARG}";
            add_ranges "${OPTARG}";
            ;;
         -)
        echo "option --, OPTARG=$OPTARG";
            break ;
            ;;
         *)
        echo "ERROR: Unrecognized option: zeoption=$zeoption OPTARG=$OPTARG";
            shift
            ;;
      esac;
   done;

   shift $((OPTIND-1)) ; #we shift away all the options we processed.
   ###### end of options handling

    # and we continue here...

   echo "we now have : remaining arguments: ${@}"
   echo "and myarray contains: ${myarray[@]}"

e, em seguida, execute-o:

$ ./toto.bash -r 2,4,6-12 -r 100-103 foo bar
we now have : remaining arguments: foo bar
and myarray contains: 2 4 6 7 8 9 10 11 12 100 101 102 103

Eu queria dar apenas dicas, mas saiba que escrever isso é melhor. Isso faz uma resposta longa, mas espero que ajude!

    
por 27.12.2012 / 14:03