批处理脚本不处理goto步骤后文件的剩余部分



我有批处理文件,写入与记录的文本文件。每个记录都需要从文件中处理。例如,如果Name == KD,则转到步骤1,否则继续执行下一步。

问题转到步骤1后,退出文件。我需要回到下一个记录继续处理DF。我确实为要返回的部分添加了标签,但它只处理KD记录。

文本文件示例:

Line Name Container
1    KD   123
2    DF   657
代码:

set txtfilepath=C:TempTest.txt
set /a cnt=0
for /f %%a in ('type "%txtfilepath%"^|find "" /v /c') do set /a cnt=%%a
echo %txtfilepath% has %cnt% lines
for /f "skip=1 tokens=1,2,3,4,5* delims=,] " %%a in ('find /v /n "" ^<   %txtfilepath%') do (
    echo.%%b - this displays variable fine.
    if %%b==DF (
        set result=true
    )  else (
        goto donotexecute
    )
    echo I am in true loop.
    :donotexecute
    echo i am in do not import loop
)
:Done

所以代码放在donotexecute标签中然后我就无法回到我最初的for循环来继续文本文件中的下一行

首先,如果您只想给环境变量赋值,请不要使用set /a(求值算术表达式)。

环境变量总是字符串类型。在算术表达式中,由环境变量直接指定或保存的每个数字都被临时转换为32位带符号整数,以便对表达式求值,最后将整数结果转换回存储在指定环境变量中的字符串。直接将数字字符串赋值给环境变量要快得多。

第二,Windows命令处理器不支持FOR循环中的标签。你需要使用子程序。
@echo off
set "txtfilepath=C:TempTest.txt"
rem Don't know why the number of lines in the files must be determined first?
set "cnt=0"
for /F %%a in ('type "%txtfilepath%" ^| %SystemRoot%System32find.exe "" /v /c') do set "cnt=%%a"
echo %txtfilepath% has %cnt% lines.
for /F "usebackq skip=1 tokens=1-5* delims=,] " %%a in ("%txtfilepath%") do (
    if "%%b" == "DF" (
        call :ProcessDF "%%c"
    ) else if "%%b" == "KD" (
        call :ProcessKD "%%c"
    )
)
echo Result is: %result%
rem Exit processing of this batch file. This command is required because
rem otherwise the batch processing would continue unwanted on subroutine.
goto :EOF

rem This is the subroutine for name DF.
:ProcessDF
echo Processing DF ...
set "result=true"
echo Container is: %~1
goto :EOF
rem The command above exits subroutine and batch processing continues
rem on next line below the command line which called this subroutine.

rem This is the subroutine for name KD.
:ProcessKD
echo Processing KD ...
echo Container is: %~1
rem Other commands to process.
goto :EOF

为了理解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

  • call /?
  • echo /?
  • find /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • type /?

exit /B也可以在使用goto :EOF的地方使用,因为这是完全相同的。在命令提示符窗口exit /?中运行以了解详细信息。有时在较大的批处理文件中,使用exit /B(用于退出批处理文件的处理)和goto :EOF(用于仅退出子例程)是有意义的。

最新更新