Prepend command output lines with date/time stamps

From time to time, I’d like to know at which point in time a server is powered off or loses its network connection when powering down. Or I’d like to know when certain things happened to a system (e.g. during problem analysis).

I found a method which can be used for any command that outputs data in intervals, using nawk. Here’s a sample for ping -s:

ping -s ${HOST} |
nawk '{"date \"+%d.%m.%Y %H:%M:%S\":"|getline date;
close("date \"+%d.%m.%Y %H:%M:%S\":");
printf ("%s %s\n", date, $0)}'

or, in U.S. notation:

ping -s ${HOST} |
nawk '{"date \"+%m/%d/%Y %H:%M:%S\":"|getline date;
close("date \"+%m/%d/%Y %H:%M:%S\":");
printf ("%s %s\n", date, $0)}'

A sample output line looks as follows:

09.01.2008 16:08:24: 64 bytes from p2x (192.168.0.10): icmp_seq=0. time=0.734 ms
09.01.2008 16:08:25: 64 bytes from p2x (192.168.0.10): icmp_seq=1. time=0.357 ms
09.01.2008 16:08:26: 64 bytes from p2x (192.168.0.10): icmp_seq=2. time=0.563 ms

The important thing is to use the same date commands before the pipe and in the close() section of nawk.

By replacing the ping -s ${HOST} command with any other command that prints output to the terminal in intervals (e.g. iostat 2 or vmstat 5), you can use any other command and prepend each output line with corresponding date/time strings. You can then use the output to create charts in OpenOffice Calc or gnuplot.

One Response to “Prepend command output lines with date/time stamps”

  1. Katsumi INOUE Says:

    Thanks for the tip, Bernd.
    I added a twist to it and wrote up an entry.
    http://blogs.sun.com/LetTheSunShineIn/entry/adding_timestamp_for_each_line

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: