21

i need to redirect a output of a command to two files say file1 and file2 file1 is a new file and file2 is already existing file where i need to append the output i have tried

This is not giving the expected results:

command > file1 > file2
Tomalak
  • 332,285
  • 67
  • 532
  • 628
user75536
  • 1,511
  • 3
  • 11
  • 5
  • Duplicate: http://stackoverflow.com/questions/76700/whats-a-simple-method-to-dump-pipe-input-to-a-file-linux, http://stackoverflow.com/questions/418896/how-to-redirect-output-to-a-file-and-stdout – S.Lott Mar 09 '09 at 09:43
  • 2
    Both those "Dupes" are specifically Linux/bash. This question is a bit more useful since it's OS agnostic. It's particularly nice having all the solutions in a single answer for comparison, glad it wasn't closed as dupe and no mods have sliced it up for being too general or some such nonsense. – Bill K Nov 02 '16 at 23:34

5 Answers5

17

You are looking for the tee command.

$ echo existing >file2
$ date | tee file1 >> file2
$ cat file2
existing
Mon Mar  9 10:40:01 CET 2009
$ cat file1
Mon Mar  9 10:40:01 CET 2009
$
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
10

For Windows (cmd.exe):

command > file1 & type file1 >> file2
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • This isn't going to work unless "command" completes quickly, the "type" part won't be executed until after (and at that point might as well be a copy). You could try running "command" in another window with some form of "Start", but then the second part will fail because windows batch files have no "tail" equivalent. You'd be better off just going with powershell for this job--or the new windows bash subsystem--or install git and use it's bash--or download tee.cmd from somewhere (I used to have a copy of tee.cmd for dos in the 80's) – Bill K Nov 02 '16 at 23:25
  • You are right, it could be copy and this is not optimal overall--but lacking `tee` it's not possible with cmd.exe. `tee` is in Windows ports of the GNU utilities, like the one that comes with git for Windows, or Chef, so it's not impossible to get. The intention of the answer was to write *something* that emulates this behavior in cmd.exe though. Others wrote the Powershell variant. – Tomalak Nov 03 '16 at 03:38
6

It will be possible using the following command.

command | tee -a file1 file2
David Z
  • 128,184
  • 27
  • 255
  • 279
dvk317960
  • 672
  • 5
  • 10
4

In PowerShell use tee-object (or its tee alias)

command | tee first-file | out-file second-file

Can also tee to a variable (e.g. for further processing).

Richard
  • 106,783
  • 21
  • 203
  • 265
0

In Linux, you can do this

command | tee file1 >> file2

Martin Thompson
  • 16,395
  • 1
  • 38
  • 56
serioys sam
  • 2,011
  • 1
  • 12
  • 10