是否有 Unix 实用程序可以将时间戳添加到 stdin? [英] Is there a Unix utility to prepend timestamps to stdin?

查看:35
本文介绍了是否有 Unix 实用程序可以将时间戳添加到 stdin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最终用 Python 为此编写了一个快速的小脚本,但我想知道是否有一个实用程序可以将文本输入其中,在每行前面加上一些文本 - 在我的特定情况下,时间戳.理想情况下,使用类似于:

I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:

cat somefile.txt | prepend-timestamp

(在你回答 sed 之前,我试过这个:

(Before you answer sed, I tried this:

cat somefile.txt | sed "s/^/`date`/"

但这只会在执行 sed 时评估一次 date 命令,因此相同的时间戳被错误地附加到每一行.)

But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)

推荐答案

可以尝试使用awk:

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

您可能需要确保 产生行缓冲输出,即它在每一行之后刷新其输出流;awk 添加的时间戳将是行尾出现在其输入管道上的时间.

You may need to make sure that <command> produces line buffered output, i.e. it flushes its output stream after each line; the timestamp awk adds will be the time that the end of the line appeared on its input pipe.

如果 awk 显示错误,请尝试使用 gawk.

If awk shows errors, then try gawk instead.

这篇关于是否有 Unix 实用程序可以将时间戳添加到 stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆