Webert S. Lima Webert S. Lima - 1 year ago 110
Linux Question

Linux bash: grep from stream and write to file

I have a log file A that is constantly updated (but it is rolled over) and I need to constantly filter it's content and write to a persistent file.

I need to:

tail -f A.log | grep "keyword" >> B.log

But this command does not write anything to

Research only got me complex stuff that is not my case. My guess is that I'm missing some simple concept.

This is not the same question marked as possible duplicate, as the grep works and I have it's output if I don't try to write it to a file. The problem is the file.

Answer Source

If just grep, without writing to the file, works, you encountered a buffering "problem". I/O buffering, unless manually implemented by the program will get handled by the libc. If the program's stdout is a termial, buffering will be line-based. If not, the libc buffers output until the buffer reached a size limit.

On Linux, meaning with glibc you can use the stdbuf command to configure that buffering:

tail -f A.log | stdbuf -oL grep "keyword" >> B.log

-oL specifies that the output stream should be line-buffered.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download