Search code examples
bashunixpipetee

Duplicate command output, print un-post-treated copy to stdout and store post-treated copy into a file


I'm trying to duplicate a command's output so I apply a post-treatment to one stream, then store it to a file while printing the original one on stdout.

Closest I could come with is:

command | tee /dev/stdout | sed 's/foo/bar/g' > out.txt

which does not work as the > captures both outputs.

I'd like to avoid using a temporary file if possible. Any clue?


Solution

  • Try

    command | tee >(sed 's/foo/bar/g' > out.txt)
    

    See ProcessSubstitution - Greg's Wiki for an explanation of >(...). In short, it causes tee to write to a path that pipes the written data as input to the sed 's/foo/bar/g' > out.txt command.