是否可以在批处理文件中使用管道标准输入流?
我希望能够将一个命令的输出重定向到我的批处理文件 process.bat
列表中,因此:
C:\>someOtherProgram.exe | process.bat
我的第一次尝试是这样的:
echo OFF
setlocal
:again
set /p inputLine=""
echo.%inputLine%
if not (%inputLine%)==() goto again
endlocal
:End
当我用 type testFile.txt | 测试它时 | process.bat
它重复打印出第一行。
还有别的办法吗?
最佳答案
set/p
不适用于管道,它从输入中提取一行(随机)。
但是您可以在 for 循环中使用 more
。
@echo off
setlocal
for /F "tokens=*" %%a in ('more') do (
echo #%%a
)
但是对于以分号开头的行,这会失败(因为 eol 的 FOR-LOOP 标准是 ;
)。
而且它不能读取空行。
但是使用 findstr 你也可以解决这个问题,它在每行前面加上行号,所以你永远不会得到空行。
然后把前缀去掉到第一个冒号。
@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
将接受空搜索字符串 ""
,并允许搜索反转。这将允许这样的事情:
@echo off
setlocal DisableDelayedExpansion
for /F "tokens=*" %%a in ('find /v ""') do (
...
关于windows - 在批处理文件中读取标准输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979747/