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" ?
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

  • 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
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
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"

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.