Reputation: 161
i'm trying to set couple of variables from "for /f" command and always get "ECHO is off" when i'm echoing them:
ipst.txt file:
1 10.1.1.10
3 10.1.3.10
8 10.1.3.10
the batch file:
@ECHO OFF
set Computerslist=ipst.txt
for /f "tokens=1,2" %%A in (%Computerslist%) do (
set StationNumber=%%A
set StationIP=%%B
echo %StationNumber%
echo %StationIP%
)
the result is:
ECHO is off.
ECHO is off.
that issue prevent me from taking the variales and use them with more loops. need your help :)
Upvotes: 2
Views: 247
Reputation: 70923
@ECHO OFF
setlocal enableextensions enabledelayedexpansion
set "Computerslist=ipst.txt"
for /f "tokens=1,2 usebackq" %%A in ("%Computerslist%") do (
set "StationNumber=%%A"
set "StationIP=%%B"
echo !StationNumber!
echo !StationIP!
)
But, as indicated in the comments, delayed expansion is only needed if the changed variable is accessed INSIDE the block where the variable is changed. So, this code
@ECHO OFF
set "Computerslist=ipst.txt"
for /f "tokens=1,2 usebackq" %%A in ("%Computerslist%") do (
set "StationNumber=%%A"
set "StationIP=%%B"
)
echo %StationNumber%
echo %StationIP%
Here, access to the variable value is not done in the same block where it where changed, so, no delayed expansion required.
EDITED - as stated in comments, this last code does not list all the lines in the file. As the for loops over them, previous values are overwritten and the variables hold only the last asigned value, that will be echoed to console. My fault, bad sample selected.
Upvotes: 1
Reputation: 4750
MC ND is correct. Choose one of these 2 ways:
@ECHO OFF
set Computerslist=ipst.txt
for /f "tokens=1,2" %%A in (%Computerslist%) do (
set "StationNumber=%%A" & echo.%%A
set "StationIP=%%B" & echo.%%B
)
or
@ECHO OFF
setlocal enabledelayedexpansion
set Computerslist=ipst.txt
for /f "tokens=1,2" %%A in (%Computerslist%) do (
set StationNumber=%%A
set StationIP=%%B
echo.!StationNumber!
echo.!StationIP!
)
Upvotes: 4