Page 1 of 1

Batch file with for loops isn't working

Posted: 07 Aug 2014 12:57
by Kligham
I'm trying to make a script that takes all the .sql files in a folder and counts the amount of "/*" and "*/" as a first token. I have the following script:

Code: Select all

FOR /F "delims=" %%a IN ('DIR /b *.sql') do (
   SET start=0
   SET end=0
   SET correct=1
   
   FOR /F "tokens=1" %%b IN (%%a) do (
      IF %%b=="/*" (
         SET /A start+=1
      )
      
      IF %%b=="*/ " (
         SET /A end+=1
      )
   )
   
   IF NOT %start%==%end% (
      ECHO NOK
   )
)


It correctly goes through all the files and the %%b also contains the first token (in this cas a string). Now the issues that I have are:
1) When I redirect the %%b to a file then it's for example: "/* " and a new line I suppose. I'm assuming this is why the IF %%b=="*/ " isn't working. Is there somehow to trim the space and the new line?
2) The incrementation does not seem to work. It's like it does not know the end variable. Is this because it is in the outer loop?
3) IF NOT %start%==%end% does not work neither. Why?

Is there anyone who can help me out with this?

Re: Batch file with for loops isn't working

Posted: 07 Aug 2014 13:21
by Squashman
Kind of hard to troubleshoot without seeing your data.

By Default, the FOR command delimits the input using a space character. If you have spaces in your output it is because you are outputting it with spaces.

When using an IF command use quotes for each of your comparisons.

When you are inside a code block you need to use delayed expansion, which means any environmental variables you create need to be referenced as !start! and !end!. You use exclamation points instead of percent signs.

The only way it is going to count your start and end is if the those symbols are at the beginning of each line

Re: Batch file with for loops isn't working

Posted: 07 Aug 2014 13:31
by Squashman
Without seeing your data I think this is what you want to do.

Code: Select all

@echo off &setlocal enabledelayedexpansion
FOR %%a IN (*.sql) do (
   SET start=0
   SET end=0
   SET correct=1
   
   FOR /F "delims=" %%b IN ('find /C "/*" ^<"%%a"') do set start=%%b
   FOR /F "delims=" %%b IN ('find /C "*/" ^<"%%a"') do set end=%%b   
   IF NOT "!start!"=="!end!" echo %%a NOT OK
)