#!/bin/bash
# echo $1 $2 $3
gsub()
{
    ## clear variable in case of failure
    _GSUB=

    ## return an error if there is no pattern specified
    [ -z "$2" ] && return 1

    ## assign the search pattern to s_srch
    s_srch=${1}
    
    if [ $3 ] ; then
     ##  assign the replacement text, if any, to rep
     rep=$2
     ## assign the string to sr2
     sr2=$3
    elif [ $2 ] ; then
     ## assign the string to sr2
     sr2=$2
    fi

    ## sr1 will hold the portion of the string that has been processed
    sr1=
    
    #echo $sr1 $sr2 $sr3
    ## loop until sr2 no longer contains the search pattern
    while :
    do
      case $sr2 in
          *$s_srch*)

              ## add the string up to the match,
              ## and the replacement text, to sr1
              sr1=$sr1${sr2%%$s_srch*}$rep

              ## remove up to the match from sr2
              sr2=${sr2#*$s_srch}
              ;;
          *) break ;;
      esac
    done
    _GSUB=$sr1$sr2
    printf "%s\n" "$_GSUB"
}

gsubold()
{
    _gsub "$@" &&
    printf "%s\n" "$_GSUB"
}

gsub_()
{
    local var=$1
    local val
    eval "val=\$$var"
    _gsub "$val" "$2" "$3" || _GSUB=
    eval "$var=\$_GSUB"
}

gsub "$1" "$2" "$3"
