0

How do I write a batch script that loops through each line in a text file and stores the line in a variable in the loop?

For example I have:

@echo off

for /F "tokens=*" %%A in (C:\Users\pmandayam\git\devops\UserRegistrationServices\scripts\file.txt) do (
    set var1=%%A
    echo %var1%
)

For some reason, the output keeps printing echo is OFF. multiple times, instead of the actual line

Kingamere
  • 9,496
  • 23
  • 71
  • 110
  • What seems to be the problem? – Mad Physicist Nov 02 '15 at 19:50
  • 1
    Either use [delayed expansion](http://ss64.com/nt/delayedexpansion.html) or `call echo %%var1%%`. – wOxxOm Nov 02 '15 at 20:00
  • 2
    Possible duplicate of [set statements don't appear to work in my batch file](http://stackoverflow.com/questions/30177307/set-statements-dont-appear-to-work-in-my-batch-file) – wOxxOm Nov 02 '15 at 20:02
  • It works with `!var1!` but what is 'variable expansion'? – Kingamere Nov 02 '15 at 20:04
  • 1
    "variable expansion" means replacement of the variable by its value; the standard method is using `%var1%`; with this syntax, the variable is expanded immediately when the command line or parenthesised block of code is parsed (immediate expansion); when using delayed expansion and `!var1!` is stated, the variable is expanded when the affected code portion is executed; to enable delayed expansion in a batch file, put `setlocal EnableDelayedExpansion`; otherwise, the `!var1!` syntax has no special effect... – aschipfl Nov 02 '15 at 20:58

0 Answers0