Batch file with for loops isn't working

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Kligham
Posts: 2
Joined: 26 Jan 2011 19:46

Batch file with for loops isn't working

#1 Post by Kligham » 07 Aug 2014 12:57

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?

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Batch file with for loops isn't working

#2 Post by Squashman » 07 Aug 2014 13:21

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

Squashman
Expert
Posts: 4486
Joined: 23 Dec 2011 13:59

Re: Batch file with for loops isn't working

#3 Post by Squashman » 07 Aug 2014 13:31

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
)

Post Reply