批处理文件如何读取管道输入并将结果写入文件? [英] How can a batch file read piped input and write the result to a file?

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

问题描述

我想编写一个Windows批处理脚本 foo.cmd ,这样当我将任何文本输入其标准输入时,它将把该文本写入一个名为foo.txt的文件中.

I want to write a Windows batch script foo.cmd such that when I pipe in any text to its standard input, it writes that text to a file called foo.txt.

echo hi | foo

上面的命令应该创建一个名为foo.txt的文件,并向其中写入文本 hi .

The above command should create a file named foo.txt and write the text hi to it.

我在 foo.cmd 中尝试了此代码.

@echo off
copy con foo.txt

但这不起作用.当我运行 echo hi |foo ,脚本只是等待我通过终端(即命令提示符"窗口)输入输入.它不会读取通过管道输入的输入.

But this doesn't work. When I run echo hi | foo, the script simply waits for me to enter input via the terminal, i.e. Command Prompt window. It doesn't read the input piped it to.

我该如何解决这个问题?

How can I solve this problem?

请注意,正在传递的文本可能有多行.

Note that the text being piped may have multiple lines.

推荐答案

您需要的只是一个简单的FINDSTR命令."^" 搜索词是一个与所有输入行匹配的正则表达式.

All you need is a single simple FINDSTR command. The "^" search term is a regular expression that matches all lines of input.

@findstr "^" >foo.txt

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

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