Sum output from file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Barty
Posts: 3
Joined: 02 Jun 2010 04:53

Sum output from file?

#1 Post by Barty » 02 Jun 2010 05:00

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

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Sum output from file?

#2 Post by aGerman » 02 Jun 2010 06:20

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

Barty
Posts: 3
Joined: 02 Jun 2010 04:53

Re: Sum output from file?

#3 Post by Barty » 02 Jun 2010 06:46

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

Post Reply