所以情况是这样的...我有两个嵌套的 if 语句,然后在它们内部有一个循环(使用 GoTo 命令和一个递增变量 - for 循环模拟:D)。正如您可能知道的那样,要将新值分配给括号内(if 语句)的变量,您必须使用延迟扩展。另外,要在 for 命令中使用变量,您必须将百分号加倍,例如 %%。我想将 for /f 命令中的标记设置为我想要的变量的值。问题是加倍感叹号没有效果。我也尝试了各种...比如使用引号、转义这些引号、使用引号替代方案,但这一切都无济于事。如果您能以任何方式提供帮助,那就太好了,因为我根本想不出任何东西:(。提前谢谢你们!
如果这没有意义,这里是代码:
@echo off
set FilePath=test.bat
set RefreshRate=3
setlocal enabledelayedexpansion enableextensions
:GetData
if defined FilePath (
if exist "%FilePath%" (
:GetLines
cls
:: This is how I find out how many lines there is in the file
set "cmd=findstr /R /N "^^" "%FilePath%" | find /C ":""
for /f %%a in ('!cmd!') do set Lines=%%a
:ShowCode
cls
set LineNum+=1
if ""!LineNum!"" GTR ""!Lines!"" GoTo Refresh
::THIS IS THE MAIN PROBLEM
for /f "tokens=%%LineNum%% delims=$" %%b in ("%FilePath%") do (
set Line%LineNum%=%%b
echo !LineNum!. | !Line%LineNum%!
GoTo ShowCode
)
)
)
:Refresh
ping localhost -n %RefreshRate% >nul
GoTo GetData
很抱歉,我没有足够的时间来使其更具可读性,但这应该会让整个事情变得更清晰。
首先:在
:: remark
括号内的代码块中既不要使用 :label
注释,也不要使用 ()
。您可以在 labels.bat
脚本中找到危害性的证据,该脚本编码在下文提供的脚本的输出中; 此处的解释:括号内的代码块中的注释。
在下一个脚本中,特定纯文本文件的非空行(参见
set "FilePath=labels.bat"
)被保存到伪数组LineAAA
,其中indexAAA
=行号。我不知道根据你的问题这是否不是偏离主题,但可以提供一些有用的线索......
@echo off
setlocal enabledelayedexpansion enableextensions
cls
set line
set "FilePath=labels.bat"
set /A "RefreshRate=3"
:GetData
if not defined FilePath (
echo %%FilePath%% not defined
goto :eof
)
if not exist "%FilePath%" (
echo %FilePath% does not exist
goto :eof
rem following 'else' (sub)statement seems to be superabundant
) else (
rem GetLines
rem This is how I find out how many lines there is in the file
set "cmd=findstr /R /N "^^" "%FilePath%" | find /C ":""
for /f %%a in ('!cmd!') do set /A "Lines=%%a"
set /A "LineNum=0"
set "Line000=@rem %FilePath%"
for /f "tokens=*" %%b in (%FilePath%) do (
set /A "LineNum+=1"
set "LineX=000000000!LineNum!"
set "LineX=!LineX:~-3!"
set "Line!LineX!=%%b"
)
call :Refresh
)
set line
rem pause
endlocal
goto :eof
:Refresh
ping localhost -n %RefreshRate% | findstr /I "Packets: statistics"
rem >nul
GoTo :eof
输出:
Environment variable line not defined
Ping statistics for ::1:
Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Line000=@rem labels.bat
Line001=@SETLOCAL enableextensions enabledelayedexpansion
Line002=@ECHO ON >NUL
Line003=if ""=="" (
Line004=rem comment
Line005=@echo rem comment
Line006=)
Line007=if ""=="" (
Line008=:: comment
Line009=@echo :: comment
Line010=)
Line011=if ""=="" (
Line012=:label
Line013=@echo :label
Line014=)
Line015=@ENDLOCAL
Line016=@goto :eof
LineNum=16
Lines=16
LineX=016
labels.bat 输出:
d:\bat>labels.bat
d:\bat>if "" == "" (
rem comment
)
rem comment
d:\bat>if "" == "" (@echo :: comment )
'@echo' is not recognized as an internal or external command,
operable program or batch file.
d:\bat>if "" == "" (@echo :label )
'@echo' is not recognized as an internal or external command,
operable program or batch file.
d:\bat>
Tokens 属性不放在括号中,它们放在引号中,无论如何都是错误的。这是第 n 到第 n 个分隔术语。
类型
for /?
举例