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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
PiotrMP006
Posts: 31
Joined: 08 Sep 2017 06:10

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

#1 Post by PiotrMP006 » 03 Aug 2022 06:38

Hi

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

ex
abcd -> ****

T3RRY
Posts: 250
Joined: 06 May 2020 10:14

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

#2 Post by T3RRY » 03 Aug 2022 13:44

I'm assuming you mean to mask input as it's entered, which is a very different task from what you've actually stated. Please correct me if I'm mistaken.

If I'm correct, a simple method:

Code: Select all

@echo off
	Set "HideInput=For %%n in (1 2)Do if %%n==2 ((set /P "=_" < NUL > "!Str!" & findstr /A:1E /V "^$" "!Str!" NUL > CON) && del "!Str!" & set /P "#=")Else Set Str="
	Setlocal EnableDelayedExpansion
	%HideInput:#=PW%Enter Password
	cls &	color 07

echo You entered: "%PW%"
Pause
Endlocal

PiotrMP006
Posts: 31
Joined: 08 Sep 2017 06:10

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

#3 Post by PiotrMP006 » 04 Aug 2022 03:59

No

I want to replace all characters in a variable with another character.

ex

abcde -> *****
abcde -> -----
abcde -> #####


Please help me

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

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

#4 Post by Aacini » 04 Aug 2022 06:12

Code: Select all

@echo off
setlocal EnableDelayedExpansion

:loop
set /P "in=Input:  "
if errorlevel 1 goto :EOF

rem Get length of input string
set "str=0%in%"
set "len=0"
for /L %%a in (8,-1,0) do (
   set /A "newLen=len+(1<<%%a)"
   for %%b in (!newLen!) do if "!str:~%%b,1!" neq "" set "len=%%b"
)

rem Replicate such a number of characters
set "out="
for /L %%i in (1,1,%len%) do set "out=!out!#"

echo Output: %out%
echo/

goto loop
Antonio

T3RRY
Posts: 250
Joined: 06 May 2020 10:14

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

#5 Post by T3RRY » 04 Aug 2022 07:44

Another way:

Code: Select all

@Echo off

	Set "Var=Some !@#$%%^& string"
	Set Var
	Call:Mask Var
	Set Var
Goto:Eof

:Mask
Setlocal DISABLEdelayedexpansion
	If "%~1" == "" Exit /b 1 
	Set "String="
	For /f "UsebackQ tokens=2 Delims=:" %%G in (`cmd /V:On /u /c  ^"^<nul set/p "=!%~1!"^"^| find /v "" ^| findstr /n "^"`)Do Call Set "String=%%String%%*"
	Endlocal & 2> nul Set "%~1=%String%"
Goto:Eof



Post Reply