在下面的 .BAT 文件中,测试 2 演示了带括号的代码块中的颜色错误,测试 3 演示了 FOR 循环中的错误,测试 4 显示了如何通过调用无操作子例程 ( call :重置ANSI)。我的问题是:
错误的性质是什么......为什么在括号内的代码块中管道到 FINDSTR 后内联颜色代码会失败?这个错误是 FINDSTR 特有的,还是更普遍的?(FINDSTR 有一些已知的错误,但我没有看到其中列出了这个。)
调用无操作子例程是缓解此错误的最佳方法吗?
代码下方是显示输出的屏幕截图,显示颜色代码在测试 2 和 3 中本应以洋红色显示的行中失败。
提前感谢任何试图提供帮助的人!
[编辑 3/26/2020:因为论坛没有在 .bat 代码的颜色代码定义中显示 Esc 字符,所以我编辑了 .bat 代码,因此它将在运行时生成 Esc 字符。]
@echo off
goto :main
:resetANSI
EXIT /B
:main
setlocal EnableDelayedExpansion
for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "ESCchar=%%E"
set "green=%ESCchar%[92m"
set "yellow=%ESCchar%[93m"
set "magenta=%ESCchar%[95m"
set "cyan=%ESCchar%[96m"
set "white=%ESCchar%[97m"
echo %white%Test 1 is NOT in a FOR loop nor within parentheses.
echo %yellow%[Test 1] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
echo %cyan%Test 1 completed.
echo %white%Test 2 is within parentheses.
( echo %yellow%[Test 2] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 2 completed.
echo %white%Test 3 is within a FOR loop.
for /L %%G in (3,1,3) do (
echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 3 completed.%white%
echo %white%Test 4 is within a FOR loop and includes a call/return after the pipe to FINDSTR.
for /L %%G in (4,1,4) do (
echo %yellow%[Test %%G] %green%This is Green, %magenta%this is Magenta, and %yellow%this is Yellow.
echo %Next, the string 'success' will be piped to FINDSTR...
echo success | findstr /R success
call :resetANSI
echo %magenta%This is supposed to be magenta, and FINDSTR found and displayed 'success'.%yellow%
)
echo %cyan%Test 4 completed.%white%
exit /B
建立在用户 vssher 尝试回答问题的基础上(vssher 在发现无法正常工作后删除了他/她的尝试)我认为我找到了最佳解决方案:将 FINDSTR 命令放在嵌套括号中。该解决方案在以下 .bat 代码的测试 3 和 4 中进行了演示,显示输出的屏幕截图显示在 .bat 代码下方: