Prepending a timestamp to each line of output from a command
I wish to prepend a timestamp to each line of output from a command. For example:
foo bar baz
[2011-12-13 12:20:38] foo [2011-12-13 12:21:32] bar [2011-12-13 12:22:20] baz
...where the time being prefixed is the time at which the line was printed. How can I achieve this?
tswhich does this quite nicely:
command | ts '[%Y-%m-%d %H:%M:%S]'
It eliminates the need for a loop too, every line of output will have a timestamp put on it.
$ echo -e "foo\nbar\nbaz" | ts '[%Y-%m-%d %H:%M:%S]' [2011-12-13 22:07:03] foo [2011-12-13 22:07:03] bar [2011-12-13 22:07:03] baz
You want to know when that server came back up you restarted? Just run
ping | ts, problem solved :D.
How have I not known about this?!?!?! This complements tail -f amazingly! `tail -f /tmp/script.results.txt | ts`
What about in cygwin? Is there something similar? It doesn't appear Joey's moreutils are there.
If it's not working, try redirecting stderr to stdout e.g. `ssh -v 127.0.0.1 2>&1 | ts`
Install by doing `sudo apt install moreutils` on Debian and `yum install moreutils` on Fedora.
I think pointing out the parameter `-s` is useful. As that displays the runtime of the command. I personally like using both `ts` and `ts -s` at the same time. Looks something like this: `command | ts -s '(%H:%M:%.S)]' | ts '[%Y-%m-%d %H:%M:%S'`. This prepends the log lines like this: `[2018-12-04 08:31:00 (00:26:28.267126)] Hai <3`