Page 1 of 1

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

Posted: 2022-Aug-03, 11:58 am
by PiotrMP006
Hi

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

ex
abcd -> ****

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

Posted: 2022-Aug-04, 5:13 pm
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

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

Posted: 2022-Aug-05, 2:50 pm
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.