I want to customize a string with * characters, except the first and last 3 characters in the string, as I don't want to print this string in logs.

For example: if the string is abctextxyz, I want it changed to abc****xyz

I tried to print the string with * except the first and last 3 characters, but hard-coding it to a 7 letters string. I would like to customize it for an arbitrary length.

If the string is of 6 character or less, it should be printed as it is.

Here is a bash script that I have created for this purpose:

echo $STRING1;
echo $STRING2;
echo $STRING3;
echo $STRING4 
  • How do you want to handle strings of 6 characters or less, print the whole string? And those of 7 and 8 characters, use three * or one or two?
    – xenoid
    Mar 9, 2020 at 8:43
  • I will make sure this logic is for more than 6 character string only , if string is 6 character or less than 6 character it will print as it is, for each character there should be * for string except first and last 3 characters . e.g ABCTESTTESTXYZ --> ABC********XYZ Mar 9, 2020 at 8:46
  • What is the status of this question? Did any of the answers help you? If yes, please upvote the answer/answers that you found helpful. If any of the answers solved your problem, please click the check mark next to it, so it turns green, to mark it as the solution. Mar 11, 2020 at 20:47
  • Thank you for your answer and it gave me different perspective to look at resolution, I am new to this forum and getting use to this nomenclature, I will make sure to upvote and update comments section accordingly. Mar 13, 2020 at 6:48

2 Answers 2


Using string manipulation to replace string with asterisks.

$ a="abctextxyz"; \
  b="${a:3:$((${#a}-6))}"; \
  echo "${a:0:3}${b//?/*}${a:(-3)}"
  • Nice one, but it does not work as the OP wants if the length of the string is smaller than 6. For example, if the string is "fdgj", the output is "fdg**dgj", while the expected output is "fdgj". Mar 9, 2020 at 10:02
  • This was quick fix , thank you! Mar 13, 2020 at 6:48

This script uses sed to replace the characters with asterisks. It also uses bc to calculate the number of asterisks that should be used and seq to define the range in the printf command.

echo "$STRING"

if [[ "$STRING_LENGTH" -lt 7 ]]; then
    echo "$STRING"
    ASTERISKS=$(printf "*%.0s" $(seq $ASTERISKS_LENGTH))
    FINAL_STRING="$(echo "$STRING" | sed -r "s/(.{3})(.*)(.{3})/\1$ASTERISKS\3/")"
    echo "$FINAL_STRING"

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.