0

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

Example :

I have,

123456789 

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

12******9 

Is there a way perhaps using

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

3 Answers3

0

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

Dababi
  • 3,355
  • 24
  • 23
0

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.

mystring="${mystring:0:2}******${mystring:8}"

You could do

mystring=${mystring/????????/${mystring{0:2}******}

If it is in a file then

sed 's/\(..\)......../\1********/' file
icarus
  • 17,920
0

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"

X Tian
  • 10,463