0

A text file contains values. These values are to be used as an argument to an executable. I tried the following to see how I can use inputs (line by line) from a file:

@echo off
for /f "tokens=*" %%i in (test.txt) do (
set n1=%%i
echo %n1%
echo "done"
)

test.txt contains numbers: Ex.

0.1
0.002
3
20

The output of the set of batch commands processed from a batch file is:

20
"done"
20
"done"
20
"done"
20
"done"

What went wrong here ?

umayfindurself
  • 123
  • 3
  • 18

1 Answers1

2

To access variables inside a code block you need delayed expansion:

@ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
for /f "DELIMS=" %%i in (test.txt) do (
    set "n1=%%~i"
    echo !n1!
    echo "done"
)

Please note: delayed expanded variables need exclams instead of percents.


In this part of code you do not need delayed expansion if you use the for loop parameter %%i as "variable":

@ECHO OFF &SETLOCAL
for /f "DELIMS=" %%i in (test.txt) do (
    echo %%i
    echo "done"
)

But you cannot make string conversion like set "n1=!n1:.0=.!" with %%i.

Endoro
  • 37,015
  • 8
  • 50
  • 63
  • sounds about right... here's some discussion http://stackoverflow.com/questions/6679907/setlocal-and-enabledelayedexpansion-usage-question – kenny Jan 25 '14 at 19:12
  • That works. I understand that !n1! is to obtain the modified value for every iteration. Why the ~ ? Additionally, It tried to perform a multiplication- set /a n2=!n1!*10 echo !n2! .The result was that I got 0 for 0.1 and 0.002 along with a 'Missing operator'. The result for the other two values was good (30 and 200) – umayfindurself Jan 25 '14 at 19:24
  • `cmd` doesn't know decimal numbers. You can use only integers. – Endoro Jan 25 '14 at 19:30
  • `%%~` the tilde is usual writing in Batch programmers to remove possibly occurring double quotes. It's not necessary here, but also not harmful. – Endoro Jan 25 '14 at 19:34
  • without the multiplication I see decimals in the cmd. i will modify my text file accordingly (0.02 instead of 0.002). And would you say I can use !n1! as an input parameter for an executable ? – umayfindurself Jan 25 '14 at 19:34
  • Yes you can pass `!n1!` as parameter. To remove one zero use this code: `set "n1=!n1:.0=.!"` – Endoro Jan 25 '14 at 19:41