Replace character in certain position in a string

Hello everyone this is my first post of many to come :slight_smile:

I am writing a script and in this script at one point i need to replace a character in a particular position in a string for example:

in the string "mystery" i would need to replace the 3rd position to an "r" so the string becomes "myrtery"

i cant use cut because the loop needs to update the string on several occations on different positions so for example next time over i need to replace the 4th position to "y" the string becomes "mirytery"

any ideas as to how I can do this?? any help is greatly appreciated

See if this can help you:

#!/usr/bin/ksh
typeset -i mC=1
mStr="abcdefghij"
while [[ ${mC} -le 10 ]]
do
   echo ${mStr} | sed "s/./M/${mC}"
   mC=${mC}+1
done
$ pos=3

$ repl=r

$ echo mystery | awk -v pos=$pos -v repl=$repl '{print substr($0,1,pos-1) repl substr($0,pos+1)}'
myrtery
$ printf "mystery" | ruby -e 's=gets; s[2]="r";puts s'
myrtery