Search code examples
windowsbatch-filecmdwindows-xp

Weird string ending in colored echo on winXP(findstr)


Recently I found out about coloring echo in batch files and everything looked good until I tried it on Windows XP. This bug(?) isn't reproducible on higher versions(at least on w7, w8)

What exactly causes . . to appear after a string when it's called with call :cecho <colors> "<string>"? How to get rid of it and still make it work on winXP and higher?

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)

call :cecho 03 "I am colorful, yay" & echo.
pause
exit

:cecho
@echo off
<nul set /p "=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1

Output:

I am colorful, yay:. .
Press any key to continue . . .

Edit: PS: I'm not interested in external programs, vbs or powershell. Pure batch solution, please.

Edit2:

Thanks to @sokin I found a solution, however @jeb's solution every time creates a file, but doesn't delete it. Therefore simple del fixes it.

@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
<nul > X set /p ".=."

call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
del "%~dp0X"
pause
exit

:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"

Solution

  • As noted, the findstr command has some strange behaviour.
    On XP it replaces the backspace character with dots.

    But when the created temporary file contains a dot instead of backspaces, the problem can be solved.
    Therefore I build the second solution, but as dbenham mentioned my original code stil can't handle some characters.

    Carlos has improved my original idea to a fast and bullet proof version at Dostips: Color function v19