Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

2 Answers 2

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.