如何将日期字符串添加到连续写入的日志文件的每一行

bmk*_*bmk 8 linux string bash logging csh

有一个长时间运行的程序,不断写入日志文件 - 如何使用Linux脚本为每个写入该文件的行添加日期字符串,忽略任何缓冲问题?

我会想象这样的事情:

tail -f logfile | ADD_DATE_TO_EACH_LINE > logfile2
Run Code Online (Sandbox Code Playgroud)

输入将是这样的:

abc
def
ghi
jkl
Run Code Online (Sandbox Code Playgroud)

输出应该类似于:

2011-06-16 18:30:59 abc
2011-06-16 18:31:00 def
2011-06-16 18:35:21 ghi
2011-06-16 18:40:15 jkl
Run Code Online (Sandbox Code Playgroud)

Ste*_*ice 25

使用perl:

command 2>&1 | perl -pe 'print scalar(localtime()), " ";'
Run Code Online (Sandbox Code Playgroud)

随着gawk:

command 2>&1 | awk '{ print strftime(), $0; fflush() }'
Run Code Online (Sandbox Code Playgroud)

更换commandtail -f logfile你的具体的例子.或者,也许您可​​以将原始程序的stdout/stderr重定向到上面的管道.


aio*_*obe 6

尝试

tail -f logfile | while read line; do echo `date` "$line" ; done
Run Code Online (Sandbox Code Playgroud)

  • +1只是一个注释:使用'date +"%y-%m-%d%H:%M:%S"`而不是简单的'date`将导致他期望的确切输出; 您还可以将重定向添加到输出文件中.(这实际上是两个音符):) (3认同)

小智 5

你可以试试这个

cat /etc/motd | xargs -d"\n" -I {} date +"%Y-%m-%d %H:%M:%S {}"
Run Code Online (Sandbox Code Playgroud)

示例输出:

2013-02-26 15:13:57 
2013-02-26 15:13:57 The programs included with the Debian GNU/Linux system are free software;
2013-02-26 15:13:57 the exact distribution terms for each program are described in the
2013-02-26 15:13:57 individual files in /usr/share/doc/*/copyright.
2013-02-26 15:13:57 
2013-02-26 15:13:57 Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
2013-02-26 15:13:57 permitted by applicable law.


小智 5

存在一个专门用于此目的的工具,它\xe2\x80\x99s ts(请参阅man ts

\n\n

例如,使用您的日志文件:

\n\n
tail -f logfile | ts '%Y-%m-%d %H:%M:%S'\n
Run Code Online (Sandbox Code Playgroud)\n\n

当然,也适用于任何在标准输出上编写的软件:

\n\n
./blabla | ts '%Y-%m-%d %H:%M:%S'\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果需要,您可以添加亚秒级精度,%.S不是%S

\n