Is there any way to replace a string with a char ?

Example :

I have,


And, I want to replace all chars from position 3 to position 8 with * , to produce this result


Is there a way perhaps using

sed -i "s/${mystring:3:5}/*/g" ?

you can assign a variable var1=123456789

echo $var1 will give 123456789

then var2="${var1:0:2}*****${var1:8:9}"

echo $var2 will give 12*****9

| improve this answer | |
  • Sorry , i was unexplicit , from position 3 of the string, i meant to say – Miucin Sebastian Jan 6 '17 at 14:05
  • ok I updated the answer – Dababi Jan 6 '17 at 14:21

It is not clear where the data is. If it is in a shell variable then

Construct a new string with the first two characters from the original, the substituted string and the trailing characters of the original. Either assign it back to the original or use it as a variable. Decide if you want to check if the original string is shorter than 8 characters.


You could do


If it is in a file then

sed 's/\(..\)......../\1********/' file
| improve this answer | |

Yes, you are on the right track.

If you want to use sed then,

  • pipe your string into sed.
  • remove -i flag
  • remove g suffix you are only substituting one string ie 45678
  • add apropriate number of character to the substitution string, ie *****

    echo ${mystring}|sed "s/${mystring:3:5}/*****/g"

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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