我想实现一个提供以下功能的shell脚本程序:
输入:
#<process id> <date time> <log level> <file name> <line number> <actual message>
1098 2007-02-28 15:23:09 WARN db_util.c 5928 Config file not found, using default values
1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:17 INFO db_util.c 5908 Connected to database
1098 2007-02-28 15:23:17 ERROR log_test.c 198 Unable to setup our satellite launch system
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite
1098 2007-02-28 15:23:21 INFO log_test.c 198 Reconnected. Initialize to launch the satellite.
电子。 G。如果通过将输入文件作为输入并且性能阈值时间为2秒来执行该实用程序,则应该生成此输出:
1098 2007-02-28 15:23:09 INFO db_util.c 5908 Connecting to database
1098 2007-02-28 15:23:18 INFO log_test.c 198 Reconnecting to launch the satellite
答案 0 :(得分:0)
在bash脚本中使用awk:
#!/bin/bash
awk -v threshold=$1 '{texttime=mktime(gensub(/-|:/," ", "g", $2" "$3))} NR>1 && texttime-prevtexttime>threshold{print prevrecord} {prevtexttime=texttime; prevrecord=$0}' $2
其中$1
是您的阈值时间(以秒为单位),$2
是您的日志文件
这个awk脚本是:
threshold
设置为$1
(-v threshold=$1
)mktime(gensub(/-|:/," ", "g", $2" "$3))
)并将其存储在awk变量texttime
(texttime=
)中。可能有一种更优雅的方式,我以前在awk
没有使用日期和时间。我确定@edmorton会让我直截了当,如果这是一种丑陋的做法。NR>1
),则texttime
变量中的值减去prevtexttime
变量中的值大于我们中的值threshold
变量(texttime-prevtexttime>threshold
)然后在变量prevrecord
(print prevrecord
)中打印值。prevtexttime
设置为texttime
中的值,并将变量prevrecord
设置为此记录的内容$0
(prevtexttime=texttime; prevrecord=$0
)$2