summary: number range parsing in sh(1)

Mitchell Wyle wyle at solaris.UUCP
Thu Jul 28 17:03:54 AEST 1988


Both Chris (the wiz) Torek <chris at mimsy.umd.edu>, and
Dave (the guru) Elliot (dce at mips.com) suggested using
IFS and case rather than sed.  Using these constructs
saves 2 forks and an exec each time!! This savings is
about 50% of the time used by the script.

My heart-felt thanks to both Chris Torek and Dave Elliot.
The net is a great place to grock unix.

Here is the code now.  Anyone care to make it even
faster?  >> grin <<   perl?  awk?   ;-)

#!/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 to send such as 1,3,8-11 -> 1 3 8 9 10 11
#
# input range is in variable $RA  ($1 for testing)

RA=$1
R=""

echo in:  $RA

SIFS="$IFS"
IFS=","
for i in $RA ; do
  R=$R" "$i
done
RA=$R
IFS=$SIFS
R=""

for tok in $RA ; do
  case $tok in 
  *-*)
    SIFS="$IFS"
    IFS='-'
    set $tok
    IFS="$SIFS"
    i=$1
    max=${2:-99}
    while test $i -le $max ; do
      R=$R" "$i
      i=`expr $i + 1`
    done ;;
  *)
    R=$R" "$tok ;;
  esac
  RA=$R
done

echo out: $RA

-- 
-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