1

How to redirect all std-output from bash to a command like 'grep' or 'sed' to filter the output and then write it to a file?

This is what I want in principle: exec > >(cat | cat >>/tmp/myoutput.txt). The last command works as expected. But if I replace the first cat with grep -v 'foo' or with sed 's/foo/bar/g' no data is written into file.

How to get the above example to work with grep or sed?

Background: I would like to filter errormessages from .xsession-errors. sed -i 's/foo/bar/g' .xsession-errors is not working because sed replaces the file .xsession-errors and future output from programms is not visible. So one option to achieve would be to replace a line in /etc/X11/Xsession with code that filters messages.

More info here:

  • I used cat 2 times to show that pipes are working like expected in subshell and to route everyting into a file. The cat is of course not needed in final version.
  • I had enough output to fill buffers, I think, because I did several times ls /usr/ to fill buffers.)
  • exec | sed ... is not working
  • 1
    Why create a sub-process and cat std-in to another cat? Have you tried exec | sed ... >> file? – billc.cn Jan 16 '16 at 0:12
  • Perhaps you just don't have enough output yet to fill a buffer? – glenn jackman Jan 16 '16 at 1:05
  • (1) It might help if you showed the actual commands you've used, rather than saying "I want to do something like cat | cat except with some other command in place of cat."  (2) I tried what I think you tried, and it worked the way you wanted.  (3) Can you do bash | sed … rather than starting bash and then redirecting its output? – Scott Jan 17 '16 at 6:19
  • Read the question several times still can't understand it...anyway, did you try the tee? – Chris.C Jan 18 '16 at 23:21
0

Example:

  1. open a bash
  2. call the command exec > >(cat | cat >>/tmp/myoutput.txt)
  3. call another command eg. `ls -R /usr'
  4. end bash with exit
  5. have a look into file /tmp/myoutput.txt, you will see the output of the lscommand
  6. if you exchange the command from step with this exec > >(sed 's/usr/--HEREAMI--/g' >/tmp/myoutput2.txt)

This is working .. at the end
So it seems, it is indeed a problem with filling buffers. Several ls /usr are not enough, but ls -R /usrfills the buffer. So now I need to figure out howto prevent buffering.

(Thanks for commenting and for requesting an example, this brought the solution.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.