I am using following snippet to add timestamp to console output
command | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }'
how to add milliseconds to it?
CodePudding user response:
Why not a simple bash solution? You can read each line and prepend a timestamp using the date
command, e.g.
command | while read line; do printf "%s %s\n" "$(date '%F %T.N')" "$line"; done
Example Use/Output
Sample lines:
$ cat dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
Timestamped output:
$ cat dat/captnjack.txt |
while read line; do printf "%s %s\n" "$(date '%F %T.N')" "$line"; done
2022-06-24 00:45:28.030 This is a tale
2022-06-24 00:45:28.031 Of Captain Jack Sparrow
2022-06-24 00:45:28.033 A Pirate So Brave
2022-06-24 00:45:28.035 On the Seven Seas.
(note: thank you @jhnc for the GNU date
N
specifier)
With bash you can also use process substitution to feed the timestamp loop, e.g.
while read line; do
printf "%s %s\n" "$(date '%F %T.N')" "$line"
done < <(command)
CodePudding user response:
Coming back to the original date
idea:
echo -ne "[$( date ' %Y-%m-%d %H:%M:%S,%3N')] "; command
CodePudding user response:
@Rohit : unless I'm missing something from the gawk
manual, I don't see it, unless you want to use the gawk
extension time
. Otherwise, this is how I get microsecs
for my various awk
s :
{m,g}awk '{ OFMT="%.15f"
print substr("",(__="gdate \47%s.%N\47" \ # gnu-date
)|getline _, close(__)) _ }'
1656047978.467053890228271
It only has 53-bit of precision (or 52, depending on who you ask about the implied bit), so those extra decimal points are mere optical illusions
The "substr()" here neither outputs anything nor affect what's being returned. It's sole functionality is to act as a temporary staging area of sorts
|
( I use substr() encapsulations as a generic way to
swap values between 2 variables w/o
using a temp var,
an external function call, or
bit-wise XOR techniques (awk specs intentionally dont offer it)
in a sense, it kinda gives a sorta similar,
but certainly not identical,
feel to more modern languages returning tuples)
That said, if you aren't constrained by gawk-only requirement
, i'm aware of 1 variant of awk
that offers millisec times without going external :
mawk2 '{ print substr("",srand(),srand()) srand() }'
#srand1656049345.921576#