Reputation: 11
hi I am trying to set a variable read from a text file. I am using a FOR cycle and I can read every line from a text but when I try to use the SET command I can't save it into a variable named: myvar. What am I doing wrong. Any ideas: this is my code:
@echo off
FOR /F "usebackq tokens=*" %%a IN (c:\users\victor\desktop\v1.txt) DO (
echo:%%a >> result.txt
set myvar=%%a
echo:%myvar%
)
@PAUSE
Upvotes: 0
Views: 108
Reputation: 79982
Within a block statement (a parenthesised series of statements)
, the entire block is parsed and then executed. Any %var%
within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block)
.
Hence, IF (something) else (somethingelse)
will be executed using the values of %variables%
at the time the IF
is encountered.
Two common ways to overcome this are 1) to use setlocal enabledelayedexpansion
and use !var!
in place of %var%
to access the changed value of var
or 2) to call a subroutine to perform further processing using the changed values.
See any of many, many, many SO entries regarding "delayedexpansion"
Upvotes: 1