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?

  • 1
    Note that you aren't getting quite what you asked for. The answers you've received are based upon the assumption that you don't mind the timestamp errors introduced by the fact that these are the times that tail writes to its standard output, not the times that the lines were written to the original file in the first place. You may well not mind, but be aware of this assumption derived from your question as it is written. – JdeBP Jun 17 '11 at 12:31

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

  • Note that xargs ignores empty lines. For my usecase that's fine but your milage may vary. – David Ongaro Feb 24 '17 at 7:34
  • This will break if xargs encounters unmatched quote " in the line. – MarSoft Apr 28 '17 at 20:11
  • 1
    I see. Maybe tail -f outputfile | tr '\n' '\0' | xargs -0IL date +"%Y%m%d_%H%M%S:L" is better in this case? Also works with empty lines then. – David Ongaro Apr 28 '17 at 23:54

Write a simple script to do that. Here's an example in 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.": $_"'

With awk:

tail -f infile | awk '{"date \"+%Y%m%d_%H%M%S\"" | getline now} {close("date")} {print now ": " $0}'
  • This prints the same time for all lines in my case, even if they appear 10 seconds appart. – Suzanne Dupéron Sep 29 '16 at 23:55
  • This prints the same time code at the front of every time, forever. – lbutlr Oct 10 '19 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.