1

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:

#!/bin/bash
STRING1="testabctest";
echo $STRING1;
STRING2=${STRING1:0:3};
echo $STRING2;
STRING3=${STRING1:(-3)};
echo $STRING3;
STRING4=$STRING2"****"$STRING3;
echo $STRING4 
4
  • 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 '20 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 – Saket Jambhale Mar 9 '20 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. – BeastOfCaerbannog Mar 11 '20 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. – Saket Jambhale Mar 13 '20 at 6:48
0

Using string manipulation to replace string with asterisks.

$ a="abctextxyz"; \
  b="${a:3:$((${#a}-6))}"; \
  echo "${a:0:3}${b//?/*}${a:(-3)}"
2
  • 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". – BeastOfCaerbannog Mar 9 '20 at 10:02
  • This was quick fix , thank you! – Saket Jambhale Mar 13 '20 at 6:48
0

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.

#!/bin/bash
STRING="fgdsfssa"
echo "$STRING"
STRING_LENGTH=${#STRING}

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

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.