Code will not iterate through file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tiggyboo
Posts: 5
Joined: 28 Oct 2011 15:06

Code will not iterate through file

#1 Post by tiggyboo » 12 Dec 2011 15:20

I have a script designed to read a text file and make parameters of the elements of each line, then act on them. However, it just returns info for the last line for as many times as there are lines in the input file. Here's the code:

Code: Select all

@Echo Off
setlocal EnableDelayedExpansion
Set _InputFile=master.txt
For /F "tokens=1-6 delims=|" %%A IN (%_InputFile%) DO (
Set _server=%%A
Set _database=%%B
Set _username=%%C
Set _pwd=%%D
Set _name=%%E
Set _type=%%F
echo Processing %_server%

if "%_type%"=="s" (
[do stuff...]
) else (
[do stuff...])
)


And here's an example input file:

Code: Select all

servera|dba|usera|xxx|DM|s
serverb|dbb|userb|yyy|PMT|m


And the output:

Code: Select all

Processing dbb
Processing dbb


I figure it must be the parameters in the for command, but I can't get it to work for the life of me... any suggestings very appreciated!

Regards, Al

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Code will not iterate through file

#2 Post by dbenham » 12 Dec 2011 15:48

This has got to be one of the most common recurring problems with people new to batch programming.

With FOR ... IN(...) DO (.....), everything is logically treated as one line and so %VAR% is expanded only once. The value will be constant throughout the lifetime of the loop, and the value will be the value that existed prior to to execution of the loop.

The solution is to use !VAR! delayed expansion instead. Delayed expansion expands the variable at execution time instead of parse time. Delayed expansion enables you to access variables values that were assigned within the loop.

To use delayed expansion you must first enable it, usually near the top of your script.

Code: Select all

setlocal enableDelayedExpansion
...
for.... do(
  ...
  set var=%%A
  ...
  if "!var!"=="value" ....
  ...
)

There can be unintended side-effects when delayed expansion is enabled, and there are various strategies to deal with them. But this is enough to get you started.

Dave Benham

tiggyboo
Posts: 5
Joined: 28 Oct 2011 15:06

Re: Code will not iterate through file

#3 Post by tiggyboo » 12 Dec 2011 16:00

Thanks very much Dave. I guess I was headed in the right direction since I had the setlocal enableDelayedExpansion in place, but it was all for naught since I was still using the %'s. Thanks again!

Post Reply