22

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?

719016
  • 4,683

4 Answers4

28

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).

7

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.": $_"'
Flimzy
  • 4,465
1

I would normally do this with perl as answered by others, but it was unavailable at the rather trimmed down Linux machine where I needed it, but the busybox awk applet was!

tail -f some_file  | awk -e '{ print strftime("%Y%m%d_%H%M%S",systime()) "\t" $0}'

As always the timestamp is for when the line was printed, not when it was written originally.

0

With awk:

tail -f infile | awk '{"date \"+%Y%m%d_%H%M%S\"" | getline now} {close("date")} {print now ": " $0}'
Prince John Wesley
  • 2,990
  • 3
  • 24
  • 13