scripts

My personal collection of scripts
git clone git://src.gearsix.net/scriptsscripts.zip
Log | Files | Refs | Atom | README | LICENSE

strindex.sh (raw) (856B)


   1 #!/bin/sh
   2 # strindex (string index)
   3 # description: finds the starting index of substring ($1) in a string ($2)
   4 # e.g.$ strindex "cat" "the cat sat on the mat"   #returns 4
   5 #
   6 # NOTES: index returned ranges from 0 - (string length)
   7 
   8 if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
   9 	echo "Usage: strindex [OPTIONS] SUBSTRING STRING"
  10 	echo ""
  11 	echo "print the starting index of SUBSTRING in STRING"
  12 	echo "-1 will be printed if SUBSTRING could not be found"
  13 	echo ""
  14 	echo "OPTIONS (must be provided before SUBSTRING STRING)"
  15 	echo "  -r      reverse provided SUBSTRING and STRING order"
  16 	exit
  17 fi
  18 
  19 if [[ "$1" = "-r" ]]; then # swap arguments (e.g. strindex "cat on mat" "mat")
  20 	shift
  21     x="${1%%$2*}"
  22     [[ "$x" = "$1" ]] && echo "-1" || echo "${#x}"
  23 else #standard usage (see e.g.$)
  24     x="${2%%$1*}"
  25     [[ "$x" = "$2" ]] && echo "-1"  || echo "${#x}"
  26 fi
  27