How to pipe awk output (with periodic, continuous input) to output file?

You have to flush the buffer to see something in memOut during the execution:

free -mto -s 1 | awk '/Mem/ { print strftime("%r") "," $4; fflush(stdout) }' >> memOut

Here's an alternative version:

while sleep 1; do sed -n "s/MemFree: */`date`, /p" /proc/meminfo; done >> memOut

For old versions of awk you may have to use system("").

Actually, fflush(stdout) is for only for recent versions of awk and gawk, as its only in the POSIX standard since December 2012.

free -mto -s 1 | awk '/Mem/ { 
    print strftime("%r") "," $4;
    system(""); # Flush output
}' >> memOut

Note that using system("") flushes every file descriptor, its full description is in the gawk manual, section "9.1.4 Input/Output Functions".


On certain versions of awk (e.g. mawk 1.3.3) you need to add the -W interactive command line flag to enable unbuffered operation with pipes.

Tags:

Pipe

Awk