Search code examples
batch-filescriptingwindows-scripting

Can we use IF condition inside the for loop in batch scripting?


set STR1= FINISHED

for /f "tokens=4,* delims=:" %a in (filename.txt) do (if %b == %STR1% (echo "SUCCESS") else (echo %b))

I am using the above code , but unable to loop through ,it's simply doing echo %b.

filename.txt :

12:38:32,249 INFO [SoapUIRunner] Finished running SoapUI testcase [Couple Order], time taken: 14124ms, status: FAILED

12:38:34,441 INFO [SoapUIRunner] Finished running SoapUI testcase [Ping], time taken: 2136ms, status: FINISHED


Solution

  • [ducking crossfire]

    Now - not so fast, pardners....

    As written, the code should execute

    (if  FINISHED == FINISHED (echo "SUCCESS" )  else (echo  FINISHED ) )
    

    but reports

     FINISHED
    

    Now the unwary would think that it's not acting logically - but unbelievably, it is.

    The point is that the comparison is performed using the token stream if %b == FINISHED. The leading space in %str1% is eaten by the parser as it's an optional separator. The processing then decides correctly that the contents of %b is not the same as FINISHED as %b contains a leading space.

    Cure to code as posted:

    for /f "tokens=4,* delims=:" %a in (filename.txt) do (if "%b" == "%STR1%" (echo "SUCCESS") else (echo %b))
    

    where the quotes teach cmd to not regard the leading space in str1 as a separator.

    Of course, if this was a line in a batch file as it should be to overcome the perpetual-retyping problem, then the metavariables should, indeed have their %s doubled.

    Tips : Use set "var1=data" for setting values - this avoids problems caused by trailing spaces. In comparisons, use if "thing1" == "thing2" ... to avoid problems caused by spaces in thing1/2.