我正在使用以下代碼段將時間戳添加到控制臺輸出
command | gawk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0 }'
如何添加毫秒?
uj5u.com熱心網友回復:
為什么不是簡單的 bash 解決方案?您可以讀取每一行并使用該命令添加時間戳date,例如
command | while read -r line; do printf "%s %s\n" "$(date '%F %T.N')" "$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.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.
(注意:感謝@jhnc 的 GNUdate N說明符)
使用 bash,您還可以使用行程替換來提供時間戳回圈,例如
while read -r line; do
printf "%s %s\n" "$(date '%F %T.N')" "$line"
done < <(command)
uj5u.com熱心網友回復:
回到最初的date想法:
echo -ne "[$( date ' %Y-%m-%d %H:%M:%S,%3N')] "; command
uj5u.com熱心網友回復:
@Rohit:除非我從gawk手冊中遺漏了一些東西,否則我看不到它,除非你想使用gawk擴展名time。否則,這就是我獲得microsecs各種awks 的方式:
{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 illusionsThe "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,我知道有 1 個變體awk提供毫秒時間而無需外部:
mawk2 '{ print substr("",srand(),srand()) srand() }'
#srand1656049345.921576#
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496517.html
