You need to put:
@setlocal enableextensions enabledelayedexpansion
at the top of your file and
endlocal
at the end.
Then you need to use the delayed expansion substitution characters.
@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
echo ---------------
set file_variable=%%a
echo file_variable=!file_variable!
echo filename=%%a
)
endlocal
C:\Documents and Settings\Pax\My Documents> qq.cmd
---------------
file_variable=1.txt
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt
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.