Setting Variables Within FOR Loops

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alleypuppy
Posts: 82
Joined: 24 Apr 2011 19:20

Setting Variables Within FOR Loops

#1 Post by alleypuppy » 04 Jan 2012 20:52

Hello again,

I need to check to see if a line (or lines) in a file is greater that 80 characters. To do this I need to set the value of %%a equal to a variable. I've noticed that the setting of a variable doesn't take effect until after the loop ha finished. How can I do this without exiting the loop? Here is my code:

Code: Select all

:FOR
      FOR /F "TOKENS=* DELIMS=" %%a IN ('TYPE "%FILE%"') DO (
      IF /I "%%a"==" " (
         ECHO(
         SET /A LINES+=1
      )
      IF /I "%%a" NEQ " " (
         CALL :STRLEN %%a
         IF /I "%LEN%" GTR "80" SET /A LINES+=2
         ECHO %%a
         IF /I "%LEN%" LSS "80" SET /A LINES+=1
      )

:STRLEN string len -- returns the length of a string
  SET "str=A!%~1!"
  SET "len=0"
  FOR /l %%A in (12,-1,0) do (
    SET /a "len|=1<<%%A"
    FOR %%B in (!len!) do IF "!str:~%%B,1!"=="" SET /a "len&=~1<<%%A"
  )
  endlocal&IF "%~2" neq "" (SET /a %~2=%len%) else SET len=%len%

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Setting Variables Within FOR Loops

#2 Post by Ed Dyreen » 09 Jan 2012 10:09

'
Try setlocal enableDelayedExpansion "!LEN!"

Code: Select all

setlocal enableDelayedExpansion
:FOR
      FOR /F "TOKENS=* DELIMS=" %%a IN ('TYPE "%FILE%"') DO (
      IF /I "%%a"==" " (
         ECHO(
         SET /A LINES+=1
      )
      IF /I "%%a" NEQ " " (
         CALL :STRLEN %%a
         IF /I "!LEN!" GTR "80" SET /A LINES+=2
         ECHO %%a
         IF /I "!LEN!" LSS "80" SET /A LINES+=1
      )
      endlocal &SET /A LINES=%LINES%
pause
exit

:STRLEN string len -- returns the length of a string
  SET "str=A!%~1!"
  SET "len=0"
  FOR /l %%A in (12,-1,0) do (
    SET /a "len|=1<<%%A"
    FOR %%B in (!len!) do IF "!str:~%%B,1!"=="" SET /a "len&=~1<<%%A"
  )
  endlocal&IF "%~2" neq "" (SET /a %~2=%len%) else SET len=%len%

Post Reply