Jean
Jean

Reputation: 22715

Filtering pipe using sed

How do I

  1. Send output of pipe to STDOUT and simultaneously
  2. Filter output of pipe and write it to a file

I tried

cat file | tee | sed 's/abc/def/g' >> log.txt

I get the desired filtered output in log.txt, but nothing is sent to STDOUT by tee

Upvotes: 1

Views: 1415

Answers (2)

John1024
John1024

Reputation: 113864

If the goal is to see the complete file on the terminal while sending the filtered file to log.txt, then try:

cat file | tee /dev/tty | sed 's/abc/def/g' >> log.txt

In this case, tee sends output to stdout which, in this case, goes to sed and also to the file /dev/tty which is your terminal.

Or, if you have bash or another advanced shell:

cat file | tee >(sed 's/abc/def/g' >> log.txt)

Here, tee sends output to stdout and also to the file that is listed on the command line. In the above, we ask bash to create a file-like object out of your sed command. That is done using the incantation >(...), also known as process substitution. Whatever tee writes to that "file" will appear as stdin to sed which will process it and send it to log.txt. In addition, tee will write to stdout which, in this case and unlike the first command above, is the terminal.

(I will assume that you are using cat file a stand-in for a more complex command rather than as a useless use of cat.)

Upvotes: 2

potong
potong

Reputation: 58438

This might work for you (GNU sed):

sed 's/abc/def/gw fileChanges' <fileIn >fileOut

This writes the changes only to fileChanges and the original file to fileOut (or to stdout if you do not provide a file).

Upvotes: 1

Related Questions