I am new to writing batch files; it's syntax makes me vomit and so I try to stay away. Long story short, I needed a quick and easy way to check a massive amount of data and export it all to a .csv file in windows. I wrote a simple little batch file to do the work for me.
I am having some issues wi开发者_Go百科th variable scope. The idea of this code is to build a string of data separated by commas and then echo the output. another file will catch the output, but that's not important.
here is some pseudo code which displays the problem I am having, I have run into this problem several times and have restructured my code significantly to try and avoid it
setlocal EnableDelayedExpansion
::pseudo code for loop
LOOP THROUGH LIST OF FILE PATHS PUTTING THEM INTO %%B do (
set str=, ::reset str
other code
if exist %%B (
other code
::echos the file path and checks if it is a specific file i need to search
echo %%B 2> NUL | find /I /N %%B "%phrase_0_%" > NUL
if %ERRORLEVEL% == 0 (
::HERE IS THE PROBLEM SEE BELOW FOR MORE INFO
type %%B 2> NUL | find /I /N "%phrase_1_%" > temp.txt
set /p var=<temp.txt
set "str=!str!%var%,"
del temp.txt
type %%B 2> NUL | find /I /N "%phrase_2_%" > temp.txt
set /p var=<temp.txt
set "str=!str!%var%,"
del temp.txt
)
) else ( ::OTHER CODE )
echo !str!
)
endlocal
Ok, here is what I think the problem is. I have been having trouble with nested variable calls. I would have used that handy for loop trick to put output of one command into a variable, but it required another level of nesting which meant even more trouble with changing the value of the variables. as you can see, i can mess with %str% inside the:
if exists %%B(
by using the setlocal EnableDelayedExpansion and !str! nonsense. but that won't work when i go another level down with
if %ERRORLEVEL% == 0
do you guys have some suggestions on what the problem might be, or what the solution might be?
Delayed expansion will work regardless of the nesting level. But you have other problems here anyway:
set /p var=<temp.txt
set "str=!str!%var%,"
What value do you expect %var%
to have there? You're setting a value and using it in two consecutive lines within a block. You need delayed expansion there as well.
精彩评论