summary: number range parsing in sh(1)

Leo de Wit leo at philmds.UUCP
Tue Aug 2 18:05:50 AEST 1988


In article <470 at solaris.UUCP> wyle at solaris.UUCP (Mitchell Wyle) writes:
|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.

I don't see how you get to a number of 50%; it depends entirely on the
parameters fed to the script. With long ranges the saving is only a
fraction of the code.

|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?   ;-)

C. But I don't think that was the original intention. If you plan to use
only sh and 'the tools', you can however speed up the range generation
considerably:


|    while test $i -le $max ; do
|      R=$R" "$i
|      i=`expr $i + 1`
|    done ;;

First you can avoid the test command: do something like:

if test $i -le $max
then
    while :
    do
        R=$R" "$i
        i=`expr $i + 1`
        case $i in
        $max) break;;
        esac
    done
fi

Since case and : are builtin, this avoids a fork and exec for each number.
Note the first test IS needed, because the program would loop forever (?)
if $i was greater than $max already (can it be?).

Second you could count with ten numbers 'at-a-time'; i and max will contain
i/10 and max/10 respectively - the start and end have to be dealt with
separately because they don't have to start with a number ending on 0 or
end with a number ending on 9. The main part becomes:

while :
do
    R=$R" "${i}0" "${i}1" "${i}2" "${i}3" "${i}4" "${i}5" "${i}6" "${i}7" "${i}8" "${i}9
    i=`expr $i + 1`
    case $i in
    $max) break;;
    esac
done

The details of the rest that is needed to make it run OK I leave up to you.
Success!

         Leo.



More information about the Comp.unix.wizards mailing list