首页 > 解决方案 > 为什么批处理处理与单数不同的数组条目?

问题描述

我有以下(简化等):

@echo off
set searchStr="AAAA"

set workingPaths[0]="C:\Docs\Me\"

set x=0

::Loop1
if defined workingPaths[%x%] (
    set currPath=%%workingPaths[%x%]%%
    rem set currPath="C:\Docs\Me\"

    call echo Searching in: %currPath%

    for %%f in (%currPath%*.doc*) do (
        findstr /s /m /I /c:%searchStr% "%%f"
    )

    set /a x+=1
    GOTO :Loop1
)   

如果我将 currPath 切换到单个赋值(当前是 rem ),它工作得非常好,但如果 currPath 被分配到数组之外,它将不起作用。

无论 currPath 是从数组还是单数赋值中设置,后续的回显都是相同的。

有人知道我哪里出错了吗?提前致谢

标签: arraysbatch-file

解决方案


我会以稍微不同的方式执行此任务,因为我会尝试更好地利用findstr.exe. 我将构建一个列表workingPaths并将它们传递给单个findstr.exe实例,使用它的/D选项。

例子:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Rem Script defined variables [please do not modify].
For /F "Delims==" %%G In ('"(Set workingPaths[) 2>NUL"') Do Set "%%G="
Set "findStr=%SystemRoot%\System32\findstr.exe"
Set "dirList="

Rem User defined variables [modify as necessary]
Set "searchStr=AAAA"
Set "searchGlob=*.doc"
Set "workingPaths[0]=C:\Docs\Me"
Set "workingPaths[1]=C:\Users\Me\Documents"
Set "workingPaths[2]=C:\Users\Me\Desktop"

Rem Directory list builder [please do not modify]
For /F "Tokens=1,* Delims==" %%G In ('"(Set workingPaths[) 2>NUL"'
) Do If Not Defined dirList (Set "dirList="%%~H"") Else (
    SetLocal EnableDelayedExpansion
    For /F "UseBackQ Delims=" %%I In ('"!dirList!"') Do (EndLocal
        Set "dirList=%%~I;"%%~H""))
If Not Defined dirList Exit /B

Rem Main search command [please do not modify]
%findStr% /D:%dirList% /I /L /M /S "%searchStr%" "%searchGlob%"

Rem Optional commands for GUI usage puposes only [remove as necessary]
Pause
GoTo :EOF

推荐阅读