Skip to content

How to Calculate the Running Total of Numbers from a File in Batch Script

Learn how to read numbers from a file and compute a running total (cumulative sum) in Windows Batch scripting, including error handling and CSV output.

A Running Total (also called a Cumulative Sum) is a sequence of partial sums where each entry is the sum of all previous values plus the current one. For example, given the numbers 5, 10, 3, the running totals are 5, 15, 18. This is commonly used in financial tracking, log analysis, and progress monitoring.

In this guide, we will demonstrate how to read numbers from a file and calculate their running total.

The Strategy: Read and Accumulate

  1. Open a file containing one number per line.
  2. Initialize a total variable to 0.
  3. For each line, add the number to total.
  4. Display or log both the current number and the running total.

Setup: Create the Input File

:: Create a sample numbers file
(
    echo 150
    echo 200
    echo 75
    echo 300
    echo 125
) > numbers.txt

Implementation Script

@echo off
setlocal enabledelayedexpansion

set "inputFile=numbers.txt"

:: Validate that the input file exists
if not exist "!inputFile!" (
    echo [ERROR] File not found: !inputFile!
    pause
    exit /b
)

set "total=0"
set "lineNum=0"

echo.
echo --- RUNNING TOTAL REPORT ---
echo.
echo  #   Value   Running Total
echo ---  -----   -------------

for /f "usebackq delims=" %%A in ("!inputFile!") do (
    :: Validate that the line contains a number
    set "val=%%A"
    set /a "check=val" 2>nul
    if !errorlevel! NEQ 0 (
        echo  [SKIP] Non-numeric line: "%%A"
    ) else (
        set /a "lineNum+=1"
        set /a "total+=val"
        echo  !lineNum!   %%A       !total!
    )
)

echo.
echo ==========================================
echo GRAND TOTAL: !total! (%lineNum% entries)
echo ==========================================
pause

Why Calculate a Running Total?

  1. Financial Tracking: Monitoring how daily expenses accumulate over a month to visualize spending trends.
  2. Log Analysis: Counting the cumulative number of errors or events over time from a system log.
  3. Progress Monitoring: Showing "total bytes downloaded so far" when processing a list of file sizes.

Important Considerations

Best Practices

Conclusion

Calculating a running total transforms a flat list of numbers into a dynamic, cumulative dataset. By reading values from a file and maintaining an accumulator variable, you build a powerful analytical tool for financial tracking, progress monitoring, and trend analysis. This technique ensures your Batch scripts can provide real-time, cumulative insights from any numeric data source.

Navigation