[英]want to add milliseconds in time stamp of console output using gawk bash
我正在使用以下代码段将时间戳添加到控制台输出
command | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }'
如何添加毫秒?
为什么不是简单的 bash 解决方案? 您可以使用date
命令读取每一行并添加时间戳,例如
command | while read -r line; do printf "%s %s\n" "$(date +'%F %T.%03N')" "$line"; done
示例使用/输出
示例行:
$ cat dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.
时间戳输出:
$ cat dat/captnjack.txt |
while read line; do printf "%s %s\n" "$(date +'%F %T.%03N')" "$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.
(注意:感谢@jhnc 提供 GNU date
%03N
说明符)
使用 bash,您还可以使用进程替换来提供时间戳循环,例如
while read -r line; do
printf "%s %s\n" "$(date +'%F %T.%03N')" "$line"
done < <(command)
回到最初的date
想法:
echo -ne "[$( date '+%Y-%m-%d %H:%M:%S,%3N')] "; command
@Rohit:除非我错过了gawk
手册中的某些内容,否则我看不到它,除非您想使用gawk
extension time
。 否则,这就是我为各种awk
获得microsecs
的方式:
{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)
也就是说,如果您不受gawk-only requirement
限制,我知道awk
的 1 个变体提供毫秒时间而无需外部:
mawk2 '{ print substr("",srand(),srand()) srand() }'
#srand1656049345.921576#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.