I got 1.txt and 2.txt in my working directory. I use the following batch to list all the files.
The batch is this:
@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
echo ---------------
set file_variable=%%a
echo file_variable=%file_variable%
echo filename=%%a
)
The result is below:
---------------
file_variable=2.txt <---------------why it is not 1.txt here??
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt
Thanks.
You need to put:
at the top of your file and
at the end.
Then you need to use the delayed expansion substitution characters.
What you're seeing without delayed expansion is that the entire
for
loop is being evaluated before running. That includes the substitution, so that%file_variable%
will be replaced with the value it held before the loop started. Using delayed expansion defers the evaluation until the actual line is executed.There are all sorts of wonderful Windows scripting tricks over at Rob van der Woude's site, containing quite a lot of different ways of doing things under Windows with various tools.
In this particular case you could get the correct output if you ECHOed
file_variable
like this:This approach is less flexible and probably less performant than the one described in @paxdiablo's answer. It's probably just a quick-and-dirty method of delaying the expansion of a variable without the need to enable the special syntax for that.