0

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

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

I tried this code in foo.cmd.

@echo off
copy con foo.txt

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.

dbenham
  • 127,446
  • 28
  • 251
  • 390
Lone Learner
  • 18,088
  • 20
  • 102
  • 200
  • Seems to be a duplicate of : http://stackoverflow.com/questions/6979747/read-stdin-stream-in-a-batch-file/6980605#6980605 – Guillaume F. Dec 30 '15 at 03:26
  • As to why your code doesn't work, the `CON` device really does mean the console, not the standard input. (There is no device name representing standard input, Windows doesn't work that way.) – Harry Johnston Dec 30 '15 at 04:50
  • @GuillaumeF. - That question requires a more complex solution than this question. – dbenham Dec 30 '15 at 04:56

1 Answers1

4

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
dbenham
  • 127,446
  • 28
  • 251
  • 390