_gsub() { ## clear variable in case of failure _GSUB= ## assign the string to sr2 sr2=$1 ## return an error if there is no pattern specified [ -z "$2" ] && return 1 ## assign the search pattern to s_srch s_srch=${2} ## assign the replacement text, if any, to rep rep=$3 ## sr1 will hold the portion of the string that has been processed sr1= ## 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 } gsub() { _gsub "$@" && printf "%s\n" "$_GSUB" } gsub_() { local var=$1 local val eval "val=\$$var" _gsub "$val" "$2" "$3" || _GSUB= eval "$var=\$_GSUB" }