在批处理文件中读取stdin流 [英] Read stdin stream in a batch file
问题描述
是否可以使用批处理文件内的标准输入管道流?
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.
有另一种方式?
推荐答案
设置/ P
不与管道的工作,它需要一个(随机)线从输入。结果
但是你可以使用更多
的for循环里面。
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循环的标准是;
)。结果
而且它无法读取空行。结果
但可以解决这个FINDSTR过,它preFIX与行号的每一行,所以你永远不会空行。结果
然后将preFIX被去除以所述第一结肠。
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
)
另外,在某些环境中(如WinRE中)不包括 FINDSTR
,一个替代 FIND.EXE
就足够了。 找到
将接受空搜索字符串,
,并允许搜索倒置。这将允许这样的事情:
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 (
set "line=%%a"
echo(!line!
)
这篇关于在批处理文件中读取stdin流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!