pipe stdout-to-file with wc

8,221

Solution 1

Use tee:

users | tee file | wc -w

Gives as output the number of users, and it writes a file with the users as content.


The case in your question:

command >file | command2

This cannot work. With >file you redirect the ouput of command to the file file and in the same the output is written to an anonymous pipe, where the command command2 reads at the other end. This is an ambiguous redirection.

The tee command will accept a file as argument, in which tee writes everything it recieves from its standard input. tee also writes everything from standard input to its standard output, where you can redirect to further commands or files.

Solution 2

There is a command to accomplish this; it's called tee:

users | tee file | wc -w

PS. (External) commands do not differ between shells; input and output redirection syntax does vary.

Share:
8,221

Related videos on Youtube

Brad B
Author by

Brad B

Updated on September 18, 2022

Comments

  • Brad B
    Brad B over 1 year

    I'm working on a lab assignment for a class, which exemplifies users | wc -w as displaying the number of users currently logged in. The instructor has asked we write the output of users to a file (users > file), while still displaying the count. My initial thought was to change the original example to simply read users > file | wc -w, but I receive the error:

    ambiguous output redirect
    

    Our college's Unix lab has us working, by default in tcsh, and I know the commands can differ between the shells. Is there a command that can accomplish this that I'm completely forgetting?

  • Martin Tournoij
    Martin Tournoij over 8 years
    It's perhaps useful to mention that the name "tee" is named after a T-splitter, which is exactly what the commands does: take some input, and "split" it to both stdout and a file; you can then further pipe stdout to other processes (wikipedia has a nice image of this).
  • chaos
    chaos over 8 years
    @Carpetsmoker Good image, that's the T, didn't know that. BTW: the manpage of tee is also very concise: tee - read from standard input and write to standard output and files
  • Brad B
    Brad B over 8 years
    Okay, thanks! I had visited the man page for tee, but it sort of threw me off, I wasn't sure that was what I needed.