How to set a variable in these batch loops?

2019-09-04 05:34发布

问题:

think I'm getting things confused here.

I've got a loop that runs all files in a folder

for /f "delims=_" %%J in ('forfiles /p "%%F" /m *.ext /c "cmd /c echo @path"')
    do start "program"  /D "c:\program files\path\to\program" /Wait program -r  %%J

%%J should represent each file if I've set this up / interpretted this correctly.

I have another loop that is looking in the xml code for each of these files and searching for a particular pattern using findstr and parsing out the Name from some tags like this:

for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%J"')
    do (set name=%%a)
echo !name!

Now I thought it would be as easy as just reusing %%J in the findstr loop but it doesn't seem to be working. When I run the code, it tells me FINDSTR: Cannot open %J and then ECHO is off

I'm guessing my problem is that it was too quick and easy to try using %%J in the next loop and that the shell isn't connecting the dots between loops.

Any ideas how I can do this? Because I need the file name in the findstr loop to always match the file in the first loop.

EDIT: Here's what the file might look like.

c:\path\to\the file name 

Here's what the output looks like:

FINDSTR: Cannot open "c:\path\
FINDSTR: Cannot open to\
FINDSTR: Cannot open the
FINDSTR: Cannot open file
FINDSTR: Cannot open name

so it would seem its a simple issue of how the shell is reading the %%J variable. This type of thing has shown up when I've forgotten to put quotes around file names before but the quotations are around %%J. I even tried double quotations but was a little relieved when that didn't fix it.

EDIT2: I changed

for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%J"')
    do (set name=%%a)

to

for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%~nJ"')
    do (set name=%%a)

and now the output is: FINDSTR: Cannot open the file name. So now at least its reading the file in full. At least it would seem that way.

回答1:

for %%J in ( ... ) do  (
    ....
    %%J is visible here, inside the do clause
    ....
) <- here %%J goes out of scope

So, you can include your second (third : %%F?) for loop inside the do clause of the first one

for %%J in ("%%F\*.ext") do (
    start "program"  /D "c:\program files\path\to\program" /Wait program -r  "%%~fJ"
    for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%J"') do (
        echo %%a
    )
)