Page 1 of 1

Sum output from file?

Posted: 02 Jun 2010 05:00
by Barty
Hello,

I need to sum the output from a file, why this doesnt work i dont know?

Code: Select all

set /A tot=0
for /f "tokens=1" %%a in (file.txt) do (

   set /A tot=%tot% + %%a
)
echo %tot%



The file looks like this:

Code: Select all

5
3
8
6
4
8


The %tot% variable is equal to the last value in the file?

Anyone knows why?


EDIT: One more question now while I'm at it, whats the difference between:

Code: Select all

echo %var%
echo.%var%


//Barty

Re: Sum output from file?

Posted: 02 Jun 2010 06:20
by aGerman
Try this:

Code: Select all

set /A tot=0
for /f "tokens=1" %%a in (file.txt) do (

   set /A tot+=%%a
)
echo %tot%

otherwise the variable %tot% will not be changed during the run tim of the for loop.

echo %var% and echo.%var% is allmost the same. If var is not defined (has no value) you will get a message if you wrote no dot ("echo is on" or something similar). If you wrote the dot you will get an empty line in this case.

Regards
aGerman

Re: Sum output from file?

Posted: 02 Jun 2010 06:46
by Barty
aGerman wrote:Try this:

Code: Select all

set /A tot=0
for /f "tokens=1" %%a in (file.txt) do (

   set /A tot+=%%a
)
echo %tot%

otherwise the variable %tot% will not be changed during the run tim of the for loop.

echo %var% and echo.%var% is allmost the same. If var is not defined (has no value) you will get a message if you wrote no dot ("echo is on" or something similar). If you wrote the dot you will get an empty line in this case.

Regards
aGerman


Aaah! Thanks aGerman for the answers! :D