Computing Staff
  • 7

Batch File For /F Loop Only Doing Last Item

  • 7

Good morning

I’ve got an incredibly long-winded (too long to post here, unfortunately, so it’s more a general question) batch file that contains

 

FOR /F %%G IN (e:\apps\dw\dump\pending_trn.txt) DO (
...do stuff here...
)

The pending_trn.txt file just contains numbers

8000003
8000070
8000912

The aim of this is to loop through each item in the file, kicking out a text file with further information on the transaction. So I’d expect to see in the target directory text files called text.8000003 and text.8000070 and text.8000912

But for some reason it only works on the last item in the file, ie. the only textfile that is created is text.8000912

I’ve got a line in the batch file that says

 

SETLOCAL EnableDelayedExpansion

Can you guys think of any other reason that the FOR /F loop would only complete the last item in the source file?

Many Thanks in advance

Share

1 Answer

  1. Hard to see without the code, but I assume you’re doing something like this:

    FOR /F %%G IN (e:\apps\dw\dump\pending_trn.txt) DO (
      stuff
      set someVar=%%G
    )
    doSomething %someVar%

    If that’s the case, then you’re using the variable outside of the loop; of course it’ll only have the last value in it.

    Or you’re doing something like this:

    FOR /F %%G IN (e:\apps\dw\dump\pending_trn.txt) DO (
      stuff
      echo %%G > SomeFile
    )
    type SomeFile

    If that’s the case, replace ‘>’ with ‘>>’.

    • 0