appending timestamp to tail -f results

I would like to have a timestamp printed in front of every line that comes out of a "tail -f outputfile", so that I know when is each line printed in. Something like:

[...]
20110617_070222:results printed here
20110617_070312:results printed here
20110617_070412:results printed here
20110617_070513:results printed here
[...]

Any ideas?


Solution 1:

It probably doesn't get any shorter than this:

tail -f outputfile | xargs -IL date +"%Y%m%d_%H%M%S:L"

Note that I used the timestamp format suggested by your question, but you're free to use anything supported by the date command (the format syntax is supported by standard BSD and GNU date).

Solution 2:

Write a simple script to do that. Here's an example in perl:

#!/usr/bin/perl
while(<>) {
    print localtime . ": $_";
}

To use the script, simply pipe your tail output through it:

tail -f outputfile | ./prepend_timestamp.pl

You could also do it inline:

tail -f outputfile | perl -pe '$_ = localtime.": $_"'

Solution 3:

With awk:

tail -f infile | awk '{"date \"+%Y%m%d_%H%M%S\"" | getline now} {close("date")} {print now ": " $0}'