如何清除批处理中的选定行而不是整个屏幕?

时间:2017-05-23 05:13:00

标签: batch-file cmd windows-console

当我们使用pause时,显示“按任意键继续......”。按任意键后,后一个文本保留,剩下的文本显示在其下方。如果我在cls之后使用pause,则整个屏幕都会被清除。

是否有任何方法只能删除“按任意键继续......”按任意键后?另外,如何仅清除选定的行而不是清除整个屏幕?

3 个答案:

答案 0 :(得分:6)

此问题有多种解决方案,但批处理不提供简单

批处理的主要问题是,您无法使用普通命令向上移动光标。

1)您可以使用cls清除屏幕并重新绘制所有必要的数据。

2)您可以使用外部程序移动光标(此程序可以动态创建),例如Move Cursor to 0,0

3)您可以滥用timeout命令返回第二行 Move cursor to screen home with TIMEOUT command!,这是Aacini

发现的一个非常酷的技巧

4)使用Windows 10,您可以使用Ansi-Escape序列来移动光标并获得许多其他效果,但它仅适用于Win10

答案 1 :(得分:3)

你也可以使用一个奇怪的技巧,它结合了一个TAB字符和几个BS字符,将光标向上移动任意数行:

1

重要:您必须确保第@echo off setlocal EnableDelayedExpansion rem Get a BS and TAB control characters for /F %%a in ('echo prompt $H ^| cmd') do set "BS=%%a" set "TAB= " & REM Be sure that TAB variable contains an Ascii 9 character rem Leave some empty lines and do a PAUSE echo Three empty lines below + pause echo/ echo/ echo/ pause rem Get width of screen buffer, set number of lines to go above for /F "tokens=2" %%a in ('mode con ^| findstr "Col"') do set /A buffWid=%%a, linesAbove=3 rem Assemble the "go above" control string with the proper number of BSs set "BSs=" set /A "cntBS = 2 + (buffWid + 7) / 8 * linesAbove" for /L %%i in (1,1,%cntBS%) do set "BSs=!BSs!!BS!" rem Move cursor up the desired number of lines echo %TAB%!BSs! echo Hello, echo World echo This line overwrites the one with PAUSE output 行有效地包含TAB(Ascii 9)字符,而不仅仅是空格。

PAUSE之前的输出:

set "TAB=    "

...并且在PAUSE之后:

Three empty lines below + pause



Presione una tecla para continuar . . .

在Windows 8.1上测试

这种方法是由DosTips用户neorobin发现的,并在this topic完整描述。

答案 2 :(得分:2)

cmd无法删除某些行。但是,我可以提供解决方法:

@echo off
rem // Enable delayed expansion which is necessary to output carriage-return characters later:
setlocal EnableDelayedExpansion
rem // Retrieve a carriage-return character:
for /F %%C in ('copy /Z "%~f0" nul') do set "CR=%%C"
rem // Retrieve a back-space character:
for /F %%C in ('echo prompt $H ^| cmd') do set "BS=%%C"
rem // Prepare message text and a string of spaces:
set "STRING=Press any key to continue . . . "
set "SPACES=                                "

rem // Use `set /P` to print message text without trailing line-break (carriage-return + line-feed):
set /P ="%STRING%" < nul
rem // Do `pause` but suppress its message text:
pause > nul
rem /* Use `set /P` to first print an invisible back-space character; this avoids a white-space
rem    character to appear first to `set /P` as it would not output such leading characters;
rem    then print a single carriage-return character to move the cursor to the beginning of the
rem    current line; then a string of spaces onto the previous message text to overwrite and so to
rem    clear it; append a single carriage-return character, so any other text is printed onto it;
rem    since there is no trailing line-break, any further text is printed at the same line: */
set /P ="%BS%!CR!%SPACES%!CR!" < nul
endlocal