How to replace a letter of string at some position

8,888

Solution 1

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}

Solution 2

Another solution with sed:

$ echo "hello" | sed 's/\(.\{2\}\)./\1a/'
Share:
8,888

Related videos on Youtube

Eng.Fouad
Author by

Eng.Fouad

Updated on September 18, 2022

Comments

  • Eng.Fouad
    Eng.Fouad over 1 year

    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
    
  • mailq
    mailq over 12 years
    Does not work if index=0 but this is your homework. (And index > len(s) )