6

I have an infinite stream of data coming out of a logger, which I am piping to grep. I would like to save the output of the grep to a file, but also include a timestamp at the beginning of each line (the time at which the line appeared). Is there an easy way to accomplish this? Assume I cannot change the output of the logger process.

4

1 回答 1

12

您可以使用and附加静态时间戳seddate

... | sed "s/^/$(date) /" >> output.txt

或者,如果您需要实时时间戳gawk,请使用strftime 函数

... | gawk '{ print strftime(), $0 }'

您可以定义自己喜欢的格式:

... | gawk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }'

如果缓冲是一个问题,不要忘记刷新每一行:

... | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush() }'

或者,使用unbuffer

unbuffer ... | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }'

如果你没有gawk,你有几个其他的选择

(a) 安装ts(来自moreutils):

... | ts '%F %T'

(b) 使用perl

... | perl -pe 's/^/localtime . " "/e'

或格式:

... | perl -MPOSIX -pe 's/^/strftime("%Y-%m-%d %H:%M:%S", localtime) . " "/e'

不要忘记,如果您需要将 GMT 格式化为您的语言环境,您可以使用gmtime而不是。localtime

(c)问一个问题

于 2012-07-31T00:01:42.550 回答