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

Kus*_*aha 2 cmd batch-file windows-console

当我们使用pause它时显示"按任意键继续......".按任意键后,后一个文本保留,剩下的文本显示在其下方.如果我clspause整个屏幕被清除后使用.

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

jeb*_*jeb 6

这个问题有多种解决方案,但批次不提供简单的解决方案.

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

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

2)你可以使用外部程序来移动光标(这个程序可以创建在运行),像移动光标到0,0

3)您可以滥用timeout命令返回第二行 使用TIMEOUT命令将光标移动到屏幕主页!,Aacini发现的一个非常酷的技巧

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


Aac*_*ini 5

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

@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
Run Code Online (Sandbox Code Playgroud)

重要提示:您必须确保该行set "TAB= "有效地包含 TAB (Ascii 9) 字符,而不仅仅是空格。

PAUSE 前的输出:

Three empty lines below + pause



Presione una tecla para continuar . . .
Run Code Online (Sandbox Code Playgroud)

...在暂停之后:

Three empty lines below + pause

Hello,
World
This line overwrites the one with PAUSE output
Run Code Online (Sandbox Code Playgroud)

在 Windows 8.1 上测试

此方法是由 DosTips 用户 neorobin 发现的,并在本主题中进行了完整描述。