Pipe only STDERR through a filter

Martin DeMello picture Martin DeMello · Sep 1, 2010 · Viewed 29.2k times · Source

Is there any way, in bash, to pipe STDERR through a filter before unifying it with STDOUT? That is, I want

STDOUT ────────────────┐
                       ├─────> terminal/file/whatever
STDERR ── [ filter ] ──┘

rather than

STDOUT ────┐
           ├────[ filter ]───> terminal/file/whatever
STDERR ────┘

Answer

Paul Rubel picture Paul Rubel · Sep 1, 2010

Here's an example, modeled after how to swap file descriptors in bash . The output of a.out is the following, without the 'STDXXX: ' prefix.

STDERR: stderr output
STDOUT: more regular

./a.out 3>&1 1>&2 2>&3 3>&- | sed 's/e/E/g'
more regular
stdErr output

Quoting from the above link:

  1. First save stdout as &3 (&1 is duped into 3)
  2. Next send stdout to stderr (&2 is duped into 1)
  3. Send stderr to &3 (stdout) (&3 is duped into 2)
  4. close &3 (&- is duped into 3)