[英]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:不幸的是 cmd.exe 像这样解析括号:
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.如果我不在
for
周围使用括号,那么anothercommand
将被视为好像它在DO
块中一样。
This forces me to output the result of each DO
block iteration to a temporary file and then read it again:这迫使我将每个
DO
块迭代的结果 output 保存到一个临时文件中,然后再次读取它:
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.您的假设是错误的, cmd.exe 不会在您的命令后关闭第一个括号。
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.但是管道的主要问题是,双方都在一个新的子 cmd.exe 实例中执行。
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.因此语法有点变化,需要在
echo
前加上@
,避免debug output。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.