Bourne sh: How to Locate Index of Element in Space-delimited List?

Bourne sh: How to Locate Index of Element in Space-delimited List?

Post by Hon-Chi N » Tue, 01 Aug 2000 04:00:00



Hi

I'm looking for a better and more efficient way of locating the index of
an element in a space-delimited list in Bourne shell script.

My current solution is writing a Bourne shell function that loops thru
the list, which is inefficient as it always traverses the whole list
regardless if the element is found at the beginning of the list.

Is there any standard/common command that does better job than my sh
function below?

What will your solution/approach be to locate the index of an element in
a space-delimited list in Bourne shell?

  # Inefficient list search as always traverse whole list.
  my_locate_elem () {
    elem=$2     # Element to be searched
    set - $1    # List must be quoted by caller

    index=0
    for e in $*; do
      if [ $e = $elem ]; then break; fi
      index=`expr $index + 1`
    done
    if [ $index -ge $# ]; then
      echo -1
      return 1
    else
      echo $index
      return 0
    fi
  }

Thanks.  Your help is appreciated.

Regards
Hon-Chi

Sent via Deja.com http://www.deja.com/
Before you buy.