How to to pipe multiple commands with 'for'

Microsoft Windows xp professional w/serv...
December 16, 2010 at 12:58:18
Specs: Windows XP
Is it possible to pipe multiple commands in a for statement?

For instance, I am trying to get the number of lines in a file assigned to a variable. There might be another way to go about this but my focus of this question is on whether it is possible to pipe multiple commands and then on a better approach for the line number to variable.

set FILE=test1.txt
for /f "tokens=* delims= " %%a in ('findstr /R /N "^" %FILE% |find.exe /v /c "" ^') do (set var=%%a)

Whenever I try anything similar to the above, I get an error, '| was unexpected at this time".

Does anyone know if this is possible?


See More: How to to pipe multiple commands with for

Report •

December 16, 2010 at 15:21:38
Use a ^ before the pipe. For example, the code below uses a pipe to count the files with extension ".flag" in a temporary directory.

FOR /F "delims=" %%a IN ('dir /B /A-D C:\temp\*.flag ^| find /c "."') DO

Report •

December 17, 2010 at 03:55:06
For your second question - whether there is a better approach - see below.

set FILE=test1.txt
for /f %%a in ('find.exe /v /c "" ^<%FILE%') do set var=%%a

Report •

December 17, 2010 at 07:42:23
Davidgpv: Thanks for your response. The statement didn't work. It seems to take the two command separately and doesn't process the pipe properly. I think there is a limitation with pipes in DOS control statements.

Klint: Thanks for your answer. That worked well.

Report •

Related Solutions

December 17, 2010 at 09:13:41
rmathew84: Can you paste what you've tried? Davidgpv's answer really should work, as long as you are using Windows XP or later (which is not DOS, by the way) then you should be able to use pipes in a FOR command as long as they are preceded by the ^ character.

Not that you need it, since you've got it working with my suggestion without a pipe, but using for ... ('command1 ^| command2') is a useful technique to have under your belt for future use.

Report •

December 17, 2010 at 09:29:59
davidgpv/Klint - The problem was somewhere between the chair and the keyboard. I had a typo in the statement and once that was fixed it worked.

Thanks davidgpv for the solution and klint for your followup.


Report •

Ask Question