views:

218

answers:

3

Windows XP

My batch file runs a command that has several lines of output. How can I count (and store in a variable) the lines of output without ever writing to the disk?

+2  A: 

Here's sample script that will count the lines in the output of the dir command.

@echo off
setlocal enabledelayedexpansion

set lc=0

for /f "usebackq delims=_" %%i in (`dir`) do (
  echo %%i
  set /a lc=!lc! + 1
)

echo %lc%

endlocal

You can substitute dir with your command and you can use quotes and specify parameters. You will have to escape some other characters though - ^, | < > and &.

If you need to not only count the lines, but also parse each line, you might have to change the token delimiter from _ (as I used in the example) to something else that will not result in the line split in multiple tokens.

Franci Penov
You can specify an empty delimiter list to prevent tokenizing with just `delims=` without anything following the `=`.
Joey
You are right, I forgot about that option. How I miss my Windows shell Programming reference book sometimes... :-)
Franci Penov
There is a Windows shell programming reference book? :O Give it to me! :D ... You also don't need delayed expansion. `set /a lc+=1` will do.
Joey
A: 

and while you are at it, you can also download GNU packages(coreutils) for windows and use the wc tool: eg

dir | wc -l
ghostdog74
A: 
dir | find /v /c "zzzxxx"

gives a line count

Andy Morris