搜索条件以查找前一小时是否存在日志



我正在创建一个 unix 脚本来检查是否为我们的一项工作生成了日志。 日志保存在文件中,时间戳如下

2017 Apr 11 13:09:54:384 - Required information will be present here.
2017 Apr 11 13:17:31:578 - Required information will be present here.

我们停留在 Seach 条件上,该条件将检查前一小时是否存在日志。

我怎么能写这个 if 语句来检查这个?

使用grep&date

grep -c "^$(date -d '-1 hour' '+%Y %b %d %H:')"

在这里,date命令生成与日志文件匹配的时间戳。然后,grep日志文件中的时间戳。-c打印匹配的文件行数。

这可能是一个有点脏的解决方案,但您可以先构造前一小时的"前缀",即2017 Apr 11 12,然后检查日志文件中有多少行匹配:

#get the prefix
prefix=$(date -d'-1 hour' +'%Y %b %d %H')
#count matching lines
cnt=$(gawk -F':' "$1=="$prefix"" test.log | wc -l)
echo $cnt

假设test.log包含

2017 Apr 11 12:09:54:384 - Required information will be present here.
2017 Apr 11 13:17:31:578 - Required information will be present here.

则上面cnt变量的值将为 1(如果 date 命令产生2017 Apr 11 12)。因此,您可以根据$cnt对脚本进行分支...

最新更新