Windows batch FOR processing files for strings
I have the following code to determine if a file has a string on the second line (::echo1, ::echo2 and ::echo3). However, when I run my code for some reason in the subroutine :_verify in the IF command inside the FOR command it completely skips the else section of IF that increases the variable %chk% and returns to :_verify, which in turn increases the number of ::echo that it is looking for in the file and searches the same file again (it needs to search each file for all 3). I tried reversing the IF command to a IF NOT and switching the else to be in front开发者_C百科 and the call :_redeem last but the same error happened. (Note: It did complete call :_verify correctly for the file containing ::echo1). It only checks each file for ::echo1 because it doesn't increase %chk% and go to :_verify again. Instead, it goes directly to goto :eof and returns to :identify to find another file that it would again, only process for ::echo1. I have added comments to help explain my script.
set gt1=1
setLocal EnableDelayedExpansion
::Identifies all files meeting the criteria (name being tmp*.tmp) and sets cap%gt1% equal the filename. Also checks to see if there are no files left (if the filename doesn't exist (i.e. it's blank because there are none left)).
:identify
set chk=1
if %gt1%==4 goto :restore
for %%A in (tmp*.tmp) do (set cap%gt1%=%%A) & call :_verify
if not exist !cap%gt1%! goto :error
goto :identify
:_verify
::Verifies that the specific file it's looking at (set as cap%gt1% in :identify) has the string ::echo1, 2 or 3 as the second line.
if %chk%==4 call :_reserve & goto :eof
for /f "skip=1" %%B in (!cap%gt1%!) do if %%B==::echo%chk% (call :_redeem) else (set /a chk=%chk%+1) & (goto :_verify)
goto :eof
:_redeem
::Renames files that are confirmed to have the string to their string name (minus the ::).
ren !cap%gt1%! echo%chk%.tmp
set /a gt1=%gt1%+1
goto :eof
:_reserve
::Subroutine used to temporairly discard files that do not meet the requirements so they will not be processed again in :identify during loopback.
if not exist temp50 mkdir temp50
move !cap%gt1%! temp50
goto :eof
:restore
::Restores files that were put in :_reserve to their previous location.
if exist %~dp0\temp50 cd temp50 & for %%C in (tmp*.tmp) do move %%C %~dp0 & cd .. & rmdir temp50
pause
:error
::Error in case it can't find all three files containing the strings.
echo Unable to find program files. Please reinstall.
echo.
pause
quit
Instead, it goes directly to goto :eof
This is the case, as you write your code to do so.
You want to write
if %chk%==4 (call :_reserve & goto :eof)
But your code works as
if %chk%==4 call :_reserve
goto :eof
You should avoid using the &
separator, better use multiple lines with parenthesis.
for %%A in (tmp*.tmp) do (
set cap%gt1%=%%A
call :_verify
)
....
if %chk%==4 (
call :_reserve
goto :eof
)
精彩评论