number range parsing in sh(1)

Mitchell Wyle wyle at solaris.UUCP
Tue Jul 26 19:20:31 AEST 1988


Is there a better way to parse numeric ranges than the following?

------------------------- snip here ------------------------- 
#!/bin/sh
#
# parse a range of numbers in the form:
#
# <range> :== <number>
#         |   <number>,range
#         |   <number>-<number>
#         |   <number>-
#
# <number>:== <digit><number>
#
# <digit> :== 0|1|2|3|4|5|6|7|8|9
#
# ...to create a list of numbers; e.g. 1,3,8-11 -> 1 3 8 9 10 11
#
# input range is in variable $RA ($1 for this example)

RA=$1
echo in:  $RA
R=""
RA=`echo $RA | sed 's/,/\ /g'`
for tok in $RA ; do
  if echo $tok | grep -s '\-' ; then
    t=`echo $tok | sed 's/-/ - /'`
    set $t
    i=$1
    max=${3:-99}
    while test $i -le $max ; do
      R=$R" "$i
      i=`expr $i + 1`
    done
  else
    R=$R" "$tok
  fi
  RA=$R
done
echo out: $RA
------------------------- snip here ------------------------- 
Is there a faster way?  How does Larry Wall's mailpatch work?

Curious minds want to know!
-- 
-Mitchell F. Wyle            wyle at ethz.uucp
Institut fuer Informatik     wyle%ifi.ethz.ch at relay.cs.net
ETH Zentrum                  
8092 Zuerich, Switzerland    +41 1 256-5237



More information about the Comp.unix.wizards mailing list