Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

windows - Read stdin stream in a batch file

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

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

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

Is there another way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
)

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
)

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 (
  ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...