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)
更换command用tail -f logfile你的具体的例子.或者,也许您可以将原始程序的stdout/stderr重定向到上面的管道.
尝试
tail -f logfile | while read line; do echo `date` "$line" ; done
Run Code Online (Sandbox Code Playgroud)
小智 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\ntail -f logfile | ts '%Y-%m-%d %H:%M:%S'\nRun Code Online (Sandbox Code Playgroud)\n\n当然,也适用于任何在标准输出上编写的软件:
\n\n./blabla | ts '%Y-%m-%d %H:%M:%S'\nRun Code Online (Sandbox Code Playgroud)\n\n如果需要,您可以添加亚秒级精度,%.S不是%S
| 归档时间: |
|
| 查看次数: |
19970 次 |
| 最近记录: |