如何在这些批处理循环中设置变量? [英] How to set a variable in these batch loops?
问题描述
认为我在这里让事情感到困惑.
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
应该代表每个文件,如果我已经设置/正确解释了这个文件.
%%J
should represent each file if I've set this up / interpretted this correctly.
我有另一个循环,正在查找这些文件中的每个文件的xml代码,并使用findstr
搜索特定的模式,并从像这样的一些标签中解析出名称:
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!
现在,我认为这就像在findstr
循环中重用%%J
一样容易,但是它似乎没有用.当我运行代码时,它告诉我FINDSTR: Cannot open %J
然后是ECHO is off
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
我猜我的问题是,在下一个循环中尝试使用%%J
太简单快捷了,而且外壳程序没有在循环之间连接点.
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.
有什么想法可以做到这一点吗?因为我需要findstr
循环中的文件名以始终与第一个循环中的文件匹配.
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.
编辑:文件的外观如下.
c:\path\to\the file name
输出内容如下:
FINDSTR: Cannot open "c:\path\
FINDSTR: Cannot open to\
FINDSTR: Cannot open the
FINDSTR: Cannot open file
FINDSTR: Cannot open name
因此,这似乎是壳层如何读取%% J变量的一个简单问题.当我之前忘记在文件名两边加上引号,但引号在%% J左右时,就会出现这种情况.我什至尝试过使用双引号,但是如果不能解决问题,我会感到放心.
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.
我更改了
for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%J"')
do (set name=%%a)
到
for /f "tokens=3 delims=<>" %%a in ('findstr /n /i "<Name>ABCDir" "%%~nJ"')
do (set name=%%a)
,现在输出为:FINDSTR: Cannot open the file name
.因此,至少现在它完整地读取了文件.至少看起来是这样.
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.
推荐答案
for %%J in ( ... ) do (
....
%%J is visible here, inside the do clause
....
) <- here %%J goes out of scope
因此,您可以在第一个循环的do
子句中包含第二个循环(第三个:%%F
?)for
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
)
)
这篇关于如何在这些批处理循环中设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!