简体   繁体   中英

Redirect the output of a for loop in cmd.exe

What I want to do is this:

(for %%a in ('command') DO something) | anothercommand

Unfortunately cmd.exe parses parentheses like this:

v open                v close
(for %%a in ('command') DO something) | anothercommand 

If I don't use parentheses around for , then the anothercommand is treated as if it was in the DO block.

This forces me to output the result of each DO block iteration to a temporary file and then read it again:

for %%a in ('command') DO echo %%a >> file.txt
anothercommand < file.txt

I'm looking for a cleaner solution that doesn't bottleneck itself because of writing and reading from storage.

Your assumption is wrong, cmd.exe does NOT close the first parenthesis after your command.
There is another problem in your code.

Working example:

( FOR /F "delims=" %%A in ('dir') do @echo ##File: %%A ) | findstr /N "^"

But the main problem of piping is, that both sides are executed in a new sub cmd.exe instance.
And there it's running in the command line context, not batch file context.
Therefore the syntax changes a bit, and it's necessary to add the @ in front of echo to avoid the debug output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM