批处理文件:FOR / F无法按预期工作

时间:2016-02-18 09:20:12

标签: batch-file batch-processing

我在批处理脚本中从* .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.

更新

我需要此脚本根据用于检查基于md5校验和的文件夹完整性的'exf.exe'的输出来同步更改的文件

3 个答案:

答案 0 :(得分:1)

如果问题的规范未描述,但基于 on examples ,我们可以做出可能或可能不正确的假设。我的假设是你想要文本文件中行的最后一个标记,所以这是一个可能的(并且更简单)解决方案:

编辑:我更改了原始方法以获得更简单的方法。

@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

答案 1 :(得分:0)

@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

一旦我们得到完整的故事就轻松修复......

答案 2 :(得分:0)

也许你需要这样的东西:

@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
    )
)