17

I have a script that outputs text to stdout. I want to see all this output in my terminal, and at the same time I want to filter some lines and save them in a file. Example:

$ myscript
Line A
Line B
Line C

$ myscript | grep -P 'A|C' > out.file

$ cat out.file
Line A
Line C

I want to see output of first command in terminal, and save the output of the second command in a file. At the same time. I tried using tee, but with no result, or better, with reversed result.

25

I want to see output of first command in terminal, and save the output of the second command in a file.

As long as you don't care whether what you are looking at is from stdout or stderr, you can still use tee:

myscript | tee /dev/stderr | grep -P 'A|C' > out.file

Will work on linux; I don't know if "/dev/stderr" is equally applicable on other *nixes.

  • 9
    /dev/stderr is common. /dev/tty (meaning the current terminal) would also work here, and it's standard. – Gilles Apr 6 '13 at 23:42
  • @Gilles: Wonderful. tee /dev/tty served wonderfully for my requirement of having to print the stdout of a script to terminal and to pipe it to the stdin of another command as well! Thankees! :-) – jamadagni Jun 7 '14 at 1:09
7
{ ... | tee /dev/fd/3 | grep -e A -e C > out.file; } 3>&1

Or with process substitution (ksh93, zsh or bash):

... | tee >(grep -e A -e C > out.file)

With zsh:

... >&1 > >(grep -e A -e C > out.file)
3

Here's another way with sed:

myscript | sed '/PATTERN/w out.file'

By default, sed prints every line so in this case stdout will be the same as stdin (i.e. you'll see the entire output of myscript on screen).
In addition, all lines matching PATTERN will be written to out.file

-1

you didn't specify how you used the tee command but this should work:

myscript | grep -P 'A|C' | tee out.file

at least it worked on my server few minutes ago...

  • 4
    But, if I'm not wrong, this way you grep also what's on screen. I want to see all output on screen, and filter only what's going into the file. – lorenzo-s Apr 6 '13 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.