How to replace all characters in a variable with another character?

Microsoft Windows
Post Reply
PiotrMP006
Posts: 19
Joined: 2021-Sep-01, 10:57 am

How to replace all characters in a variable with another character?

Post by PiotrMP006 »

Hi

How to replace all characters in a variable with another character?

ex
abcd -> ****
bluesxman
Posts: 10
Joined: 2021-Jul-26, 3:41 pm

Re: How to replace all characters in a variable with another character?

Post by bluesxman »

I don't think there's a straight forward way to do that. You could use this

https://ss64.com/nt/syntax-strlen.html

To measure the string length and then form a string of * of the right length

So, for example:

Code: Select all

@echo off
set "foo=qwertyuiop"
set "bar="
call :strlen foo foo_len

setlocal EnableDelayedExpansion
for /l %%a in (1 1 %foo_len%) do set "bar=!bar!*"
endlocal & set "bar=%bar%"
set foo
set bar

goto:eof
:strlen  StrVar  [RtnVar]
  setlocal EnableDelayedExpansion
  set "s=#!%~1!"
  set "len=0"
  for %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if "!s:~%%N,1!" neq "" (
      set /a "len+=%%N"
      set "s=!s:~%%N!"
    )
  )
  endlocal&if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b
User avatar
Simon Sheppard
Posts: 190
Joined: 2021-Jul-10, 7:46 pm
Contact:

Re: How to replace all characters in a variable with another character?

Post by Simon Sheppard »

If this is to represent a password, it is worth considering do you really need to represent the right number of characters?
Hiding the length of a password is generally good security, then you can just display a fixed line of *******'s

OTOH if this is something like a username or email address, then it may be helpful to display the first few characters.

For masking password input as it is being entered there are a few options on StackOverflow.
Post Reply