【问题标题】:Batch for loop w/ multiple commands带有多个命令的批处理循环
【发布时间】:2016-03-29 22:18:06
【问题描述】:

知道为什么这不起作用吗?我正在尝试创建一个文件,扫描当前目录中的所有批处理文件以查找特定字符串(123456),如果找到则继续:end。如果未找到,该文件应将自身复制到扫描的文件中并继续扫描下一个文件。任何想法和提示表示赞赏!干杯!

    for %%f in (*.bat) do (
        set A=%%f
        set file=%A%
        findstr "123456" %file%
        if %errorlevel%==0 goto end
        copy %0 %A%
        )
    :end

我测试了以下代码:

    SETLOCAL EnableExtensions EnableDelayedExpansion
    for %%f in (*.bat) do (
         set A=%%~f
         set file=%A%
        findstr "123456" %file%
        if %errorlevel%==0 goto end
        copy %0 %A%
        )
    :end

并且代码没有执行 goto end 命令。输出如下所示:

    C:\Users\Epidex98\Desktop\routine>(
    set A=ir.bat
     set file=
      findstr "123456"
     if 0 == 0 goto end
     copy "C:\Users\Epidex98\Desktop\routine\ir.bat"
    )

【问题讨论】:

  • 记得在一个文件夹中进行测试,该文件夹包含您需要的其他脚本的唯一副本。

标签: string batch-file for-loop


【解决方案1】:
SETLOCAL EnableExtensions EnableDelayedExpansion
for %%f in (*.bat) do (
    set A=%%~f
    set file=!A!
    findstr "123456" !file!
    if !errorlevel!==0 goto :end
    copy %0 !A!
    )
:end

或更简单

SETLOCAL EnableExtensions EnableDelayedExpansion
for %%f in (*.bat) do (
    findstr "123456" "%%~f"
    if !errorlevel!==0 goto :end
    copy %0 "%%~f"
    )
:end

但是,如果由于某种原因您不能应用延迟扩展:

SETLOCAL EnableExtensions DisableDelayedExpansion
for %%f in (*.bat) do (
    set A=%%f
    call :proc
    if errorlevel 0 goto :end
    copy %0 %%f
    )
rem next command skips :proc subroutine 
goto :end

:proc
  set file=%A%
  findstr "123456" %file%
  set /A myerror=%errorlevel%-1
exit /B %myerror%

:end 

资源(必读):

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 2013-01-25
    • 2011-01-16
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    相关资源
    最近更新 更多