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:

#!/bin/bash
index= # let say 2
s='Hello'
echo ${s/$index/'a'} # This should print Healo
link|improve this question

feedback

2 Answers

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:

#!/bin/bash
index=2
s=Hello
echo ${s:0:index-1}a${s:index}
link|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
feedback

Another solution with sed:

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

Your Answer

 
or
required, but never shown

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