批处理文件:FOR /F 没有按预期工作

Batch File: FOR /F doesn't work as expected

我在批处理脚本中读取 *.txt 文件中的行以获取文件列表时遇到问题。 如果我的文件包含类似

的内容
File does not exist: release\devpath\readme.txt
File does not exist: release\mainline\readme!!!.txt
2 errors.

我的批次是

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set count_to_sync=-1
for /f  "tokens=*" %%i in (bubu.txt) do (
    set line=%%i
    echo %%i

    if "!line:~0,9!" == "MD5 FAIL:"  (
        set /A count_to_sync+=1
        set list[!count_to_sync!]=!line:~10!
    )
    if "!line:~0,20!" == "File does not exist:"  (
        set list[!count_to_sync!]=!line:~21!
        set /A count_to_sync+=1
    )
)

IF "%count_to_sync%" == "-1" (
    ECHO Nothing to sync
) ELSE (
    ECHO Files to sync
    for /F "tokens=2 delims==" %%s in ('set list[') do (
        echo %%s
    )
)

输出为

File does not exist: release\devpath\readme.txt
File does not exist: release\mainline\readme.txt
2 errors.
Files to sync
release\devpath\readme.txt
release\mainline\readme.txt

还有'!!!'缺少第二行。

我知道如果我从批处理中删除 SETLOCAL ENABLEDELAYEDEXPANSION 输出将是

File does not exist: release\devpath\readme.txt
File does not exist: release\mainline\readme!!!.txt
2 errors.

第一部分没问题,但由于禁用了延迟扩展,提取将无法进行。

如何获得正确的输出? 谢谢

更新

具有所有类型行的输入文件

File does not exist: release\devpath\readme.txt
File does not exist: release\mainline\readme!!!.txt
MD5 FAIL: exf.exe
2 errors.

更新

我需要这个脚本根据 'exf.exe' 的输出同步更改的文件,用于根据 md5 校验和

检查文件夹的完整性
@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q35477317.txt"
ECHO Files to sync
FOR /f "usebackqtokens=4*delims=: " %%a IN ("%filename1%") DO ECHO(%%b

GOTO :EOF

您需要更改 sourcedir 的设置以适合您的情况。

我使用了一个名为 q35477317.txt 的文件,其中包含您的数据用于我的测试。

不清楚您为什么采取您的方法 - 有什么您没有告诉我们的吗?


@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q35477317.txt"
ECHO Files to sync
FOR /f "usebackqtokens=1*delims=:" %%a IN ("%filename1%") DO (
 FOR /f "tokens=*" %%c IN ("%%b") DO ECHO(%%c
)
GOTO :EOF

一旦我们得到完整的故事就很容易修复...

也许您需要这样的东西:

@ECHO OFF
rem SETLOCAL ENABLEDELAYEDEXPANSION
set count_to_sync=-1
for /f  "tokens=*" %%i in (bubu.txt) do (
    set line=%%i
    echo %%i

    SETLOCAL ENABLEDELAYEDEXPANSION

    if "!line:~0,9!" == "MD5 FAIL:"  (
        set /A count_to_sync+=1
        set list[!count_to_sync!]=!line:~10!
    )
    if "!line:~0,20!" == "File does not exist:"  (
        set list[!count_to_sync!]=!line:~21!
        set /A count_to_sync+=1
    )

    ENDLOCAL
)

IF "%count_to_sync%" == "-1" (
    ECHO Nothing to sync
) ELSE (
    ECHO Files to sync
    for /F "tokens=2 delims==" %%s in ('set list[') do (
        echo %%s
    )
)

当问题的规格未描述,而是基于示例时,我们可以做出可能是也可能不是的假设正确的。我的假设是您想要 文本文件中行的最后一个标记,因此这是一个可能的(并且更简单的)解决方案:

编辑:我将原来的方法更改为更简单的方法。

@echo off
setlocal

set "msg=Nothing to sync"
(for /F "tokens=3,5" %%a in (bubu.txt) do (
   set "msg=Files to sync"
   if "%%b" neq "" (echo %%b) else echo %%a
)) > list.txt 

echo %msg%
type list.txt