在批处理文件中读取标准输入流 [英] Read stdin stream in a batch file

查看:28
本文介绍了在批处理文件中读取标准输入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在批处理文件中使用管道标准输入流?

Is it possible to use a piped stdin stream inside a batch file?

我希望能够将一个命令的输出重定向到我的批处理文件 process.bat 列表中:

I want to be able to redirect the output of one command into my batch file process.bat list so:

C:>someOtherProgram.exe | process.bat

我的第一次尝试看起来像:

My first attempt looked like:

echo OFF
setlocal

:again
set /p inputLine=""
echo.%inputLine%
if not (%inputLine%)==() goto again

endlocal
:End

当我用 测试它时,输入 testFile.txt |process.bat 重复打印第一行.

When I test it with type testFile.txt | process.bat it prints out the first line repeatedly.

还有别的方法吗?

推荐答案

set/p 不适用于管道,它需要输入一行(随机).
但是你可以在 for 循环中使用 more.

set /p doesn't work with pipes, it takes one (randomly) line from the input.
But you can use more inside of an for-loop.

@echo off
setlocal
for /F "tokens=*" %%a in ('more') do (
  echo #%%a
)

但是这会以分号开头的行失败(因为 eol 的 FOR-LOOP 标准是 ;).
它无法读取空行.
但是使用 findstr 你也可以解决这个问题,它在每一行前面加上行号,所以你永远不会得到空行.
然后前缀被删除到第一个冒号.

But this fails with lines beginning with a semicolon (as the FOR-LOOP-standard of eol is ;).
And it can't read empty lines.
But with findstr you can solve this too, it prefix each line with the linenumber, so you never get empty lines.
And then the prefix is removed to the first colon.

@echo off
setlocal DisableDelayedExpansion

for /F "tokens=*" %%a in ('findstr /n $') do (
  set "line=%%a"
  setlocal EnableDelayedExpansion
  set "line=!line:*:=!"
  echo(!line!
  endlocal
)

或者,在某些不包含 findstr 的环境(如 WinRE)上,使用 find.exe 的替代方案可能就足够了.find 将接受空搜索字符串 "",并允许搜索反转.这将允许这样的事情:

Alternatively, on some environments (like WinRE) that don't include findstr, an alternative with find.exe might suffice. find will accept a null search string "", and allows search inversion. This would allow something like this:

@echo off
setlocal DisableDelayedExpansion

for /F "tokens=*" %%a in ('find /v ""') do (
  ...

这篇关于在批处理文件中读取标准输入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆