Jump to content

batch file: sumcol.bat


Recommended Posts

I have found that I need this functionality every now and then and this batch file is quicker than having to dump data into an Excel spreadsheet. I posted it here because others may find it useful, too.

:)

-John

@echo off

rem sumcol.bat
rem -John Taylor
rem Aug-20-2007
rem
rem Computes the numeric sum of a given column of data
rem mawk.exe is from: http://www.klabaster.com/freeware.htm#mawk
rem
rem Example:
rem cd c:\windows\system32
rem dir *.dll | findstr /i /e ".dll" | sumcol 4
rem ----
rem now compare this to the output of:
rem dir *.dll | findstr "File(s)"

setlocal

set COL=%1
set FNAME=%2

if not defined COL goto USAGE

:RUN
rem for debugging...
rem mawk.exe "{ gsub(/,/, '', $%COL%); SUM += int($%COL%); print NR' 'SUM} END { print 'sum: 'SUM }" %FNAME%
mawk.exe "{ gsub(/,/, '', $%COL%); SUM += int($%COL%) } END { printf('%%15.0f\n', SUM) }" %FNAME%
goto END

:USAGE
@echo.
@echo Usage:
@echo %0 [ column # ] [ filename ]
@echo column numbers start at 1
@echo filename is optional, this will otherwise read from standard-in
@echo.
@echo you can also use NF for the column #, which means the last column
@echo (NF-1) means the 2nd to the last column, (NF-2) means the 3rd to the last column, etc.
@echo.
goto END

:END
endlocal

Edited by jftuga
Link to comment
Share on other sites


Nice :), but if I may, the same can be made in "pure" batch, as long as data in the chosen column are integers.

A quick example:

file dirlist.cmd:

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
dir /-C %1 | find /i "%~x1" >dir.txt

file addsize.cmd

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SET TOTAL=
rem SET COL=%1
rem SET FNAME=%2
FOR /F "tokens=%1" %%A in (%2) DO CALL :addsize %%A
ECHO TOTAL is %TOTAL%
GOTO :EOF

:addsize
rem SET size=%1
SET /A TOTAL=%TOTAL%+%1
GOTO :EOF

(if data is "space" or "tab" separated, otherwise one needs to add a delims= statement in the FOR loop)

Run:

dirlist.cmd c:\windows\system32\*.dll

and then:

addsize.cmd 3 dir.txt

jaclaz

Edited by jaclaz
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...