Is it possible to echo some non-printable characters in batch/cmd?

早过忘川 提交于 2019-12-05 13:10:30

You need two hacks - one to define a carriage return character, and another to echo a line of text without issuing the newline character.

1) Define carriage return.

:: Define CR to contain a carriage return (0x0D)
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"

Once defined, the value can only be accessed via delayed expansion - as in !CR!, not %CR%.

2) Print text to the screen without issuing a newline

<nul set /p "=Your message here"

This will fail if the string starts with a =.

Also, leading quotes and/or white space may be stripped, depending on the Windows version

Putting it all together

@echo off
setlocal enableDelayedExpansion

:: Define CR to contain a carriage return (0x0D)
for /f %%A in ('copy /Z "%~dpf0" nul') do set "CR=%%A"

<nul set/p"=Part 1 - press a key!CR!"
pause >nul
<nul set/p"=Part 2 - press a key!CR!"
pause >nul
<nul set/p"=Part 3 - Finished   !CR!"

Note that I put the !CR! at the end of each message in preparation for the next. You cannot put the !CR! at the beginning because leading white space will be stripped.

Somewhere along the line, "echo\" works to print a [cr] line. Great for ending an output from some other command that doesn't put [cr] at the end. I've used this for sending CR to files as in IPconfig | find "Reply" >>myip.txt and then echo\ >>myip.txt

Building on dbenham's post, I have the following routines that work in Win7 and mostly editable in Notepad; however, I used Scite to generate the backspace, ALT+008, character. It differs slightly by first clearing the row, and placing the cursor at the end of the text. Here are the routines:

:RECHO
<nul set/p"=backspace!CR!tabtabtabtabtabtabtabtabtabtab"
<nul set/p"=backspace!CR!%*"
GOTO :EOF
:NECHO
<nul set/p"=backspace!CR!tabtabtabtabtabtabtabtabtabtab"
ECHO backspace!CR!%*
GOTO :EOF

dbenham's example modified:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

FOR /F %%a IN ('copy /Z "%~dpf0" nul') DO SET "CR=%%a"
SET "BS="

ECHO Testing CR. This line a regular echo ...
CALL :RECHO Part 1 - press a key
pause >nul
CALL :RECHO Part 2 - press a key
pause >nul
CALL :NECHO Part 3 - Finished
ECHO Testing CR. This line a regular echo ...
GOTO END

:RECHO
<nul set/p"=!BS!!CR!                                                "
<nul set/p"=!BS!!CR!%*"
GOTO :EOF

:NECHO
<nul set/p"=!BS!!CR!                                                "
ECHO !BS!!CR!%*
GOTO :EOF

:END
ENDLOCAL
EXIT /B

When copying the above script, make sure the backspace character is preserved.

    SET "BS=backspace"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!