Preserve spaces with <Nul set /p
-
26-12-2019 - |
Question
I'm trying to create a typewriter effect but SET /P is stripping the spaces since I'm on win7. Is there another way or a trick I'm missing?
Here is the code I've come up with so far:
@echo off
setlocal enabledelayedexpansion
set text=This is a test
call :strlen len text
for /l %%b in (0,1,%len%) do (
set /a T=!random! %% 3
ping -n !T! 127.0.0.1>nul
<nul set /p=!text:~%%b,1!
)
exit /b
:strlen <resultVar> <stringVar>
setlocal EnableDelayedExpansion
set "s=!%~2!#" & set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" ( set /a "len+=%%P" & set "s=!s:~%%P!" ))
endlocal &set "%~1=%len%"
exit /b
Solution
If output is strictly for the screen, and never redirected to a file, then there is a simple solution using a backspace character. Prefix each SET /P output with some printable character, followed by a backspace, followed by your desired string.
@echo off
setlocal enabledelayedexpansion
:: Define BS to contain backspace character
for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "BS=%%A"
set text=This is a test
call :strlen len text
for /l %%b in (0,1,%len%) do (
set /a T=!random! %% 3
ping -n !T! 127.0.0.1>nul
<nul set /p=.!BS!!text:~%%b,1!
)
exit /b
:strlen <resultVar> <stringVar>
setlocal EnableDelayedExpansion
set "s=!%~2!#" & set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" ( set /a "len+=%%P" & set "s=!s:~%%P!" ))
endlocal &set "%~1=%len%"
exit /b
The problem with the above is the dot and backspace characters will appear in any output that is redirected to a file. Another possible problem is the technique fails if the cursor is at the last character position on the line because a linefeed will automatically be issued after the dot, and then the backspace cannot back up to the prior line.
If you must redirect output to a file, or if you want a robust solution that works in all cases, then jeb has a very clever solution at Output text without linefeed, even with leading space or =.