How to Output to Stdout and Grep into a File Simultaneously

greppipestdouttee

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.

Best Answer

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.

Related Question