Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose I want to replace the nth letter of some string, how can I do that?

I tried something like this but it's not correct:

index= # let say 2
echo ${s/$index/'a'} # This should print Healo
share|improve this question
up vote 2 down vote accepted

There is a Advanced Bash-Scripting Guide that shows you how to do substring and concatenation.

Let's say:

echo ${s:0:index-1}a${s:index}
share|improve this answer
Does not work if index=0 but this is your homework. (And index > len(s) ) – mailq Oct 5 '11 at 22:07

Another solution with sed:

$ echo "hello" | sed 's/\(.\{2\}\)./\1a/'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.