Output to stdout and at the same time grep into a file

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.


{ ... | 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)

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