Take the 2-minute tour ×
Server Fault is a question and answer site for professional 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:

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

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:

#!/bin/bash
index=2
s=Hello
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
add comment

Another solution with sed:

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

Your Answer

 
discard

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.