如何获取Windows批处理文件中的管道输入? [英] How to get piped input in windows batch file?

查看:225
本文介绍了如何获取Windows批处理文件中的管道输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用像xxx yyy | deal_everyline.bat这样的命令,其中命令xxx yyy会生成一些输出.当我在控制台中使用deal_everyline.bat时,一切正常运行.但是,当我用cat A.txt | deal_everyline.bat测试它时,它仅输出第一行.我应该怎么做才能获得所有线路?

I want to use command like xxx yyy | deal_everyline.bat, where the command xxx yyy will generate some output. When I use deal_everyline.bat in console, everything runs normally. However, when I test it with cat A.txt | deal_everyline.bat, it only output the first line. What should I do to get all lines?

@echo off
:loop
set input=
set /p input=
if "%input%" neq "" (
    echo %input%
    goto loop
)

推荐答案

penknife建议将MOREFOR /F一起使用,但这会损坏制表符,并且挂起了64K行输入.最好使用FINDSTR "^".奇怪的FOR/F选项语法是一种禁用EOLDELIMS选项的方法,以便非空白行被准确保留,只要它们是<. 〜8191字节长.

penknife suggests using MORE with FOR /F, but that will corrupt tabs, and it hangs at 64K lines of input. Better to use FINDSTR "^". The odd FOR /F options syntax is a way to disable both the EOL and DELIMS options so that non-blank lines are preserved exactly, as long as they are < ~8191 bytes long.

@echo off
for /f delims^=^ eol^= %%A in ('findstr "^"') do (
  echo(%%A
)

上面的代码将跳过空行.如果要保留它们,则使用FINDSTR/N选项为每行添加行号前缀,后跟冒号,将值保存在环境变量中,然后使用变量扩展删除前缀.必须使用FOR循环中的延迟扩展来扩展变量,但是在扩展%%A时不能启用延迟扩展,否则会破坏!字符.因此,延迟扩展可以在循环内打开和关闭

The above code will skip empty lines. If you want to preserve them, then use the FINDSTR /N option to prefix each line with the line number followed by a colon, save the value in an environment variable, and then use variable expansion to strip the prefix. Variables must be expanded with delayed expansion within the FOR loop, but delayed expansion cannot be enabled when %%A is expanded, else it will corrupt ! characters. So the delayed expansion is toggled on and off within the loop

@echo off
setlocal disableDelayedExpansion
for /f delims^=^ eol^= %%A in ('findstr /n "^"') do (
  set "ln=%%A"
  setlocal enableDelayedExpansion
  set "ln=!ln:*:=!"
  echo(!ln!
  endlocal
)

如果要在迭代过程中保留环境变量的更改,请调用具有延迟扩展功能的子例程.但是请注意,变量的正常百分比扩展可能会失败,具体取决于内容.例如,未用引号引起的<>&|都会引起问题.

If you want to preserve environment variable changes across iterations, then CALL out to a subroutine with delayed expansion constantly off. But beware that normal percent expansion of variables can fail depending on the content. For example unquoted <, >, &, and | will all cause problems.

@echo off
setlocal disableDelayedExpansion
for /f delims^=^ eol^= %%A in ('findstr /n "^"') do (
  set "ln=%%A"
  call :processLine
)
exit /b

:processLine
set "ln=%ln:*:=%"
echo(%ln%
exit /b

这篇关于如何获取Windows批处理文件中的管道输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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