bash 过去一小时的 Grep 消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38054442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:49:47  来源:igfitidea点击:

Grep messages for the last hour

bashgrep

提问by Carla

I have an application which emits logs in this format:

我有一个以这种格式发出日志的应用程序:

00:00:10,799 ERROR [stderr] (http-prfilrjb08/10.1.29.34:8180-9)     {}:return code:  500

I would need to monitor for new ERRORs in the log file, happened in the last hour. Looking at some tutorials I've come up with the following grep:

我需要监视日志文件中的新错误,发生在过去一小时。查看一些教程,我想出了以下 grep:

 grep "^$(date -d -1 hour +'%H:%M:%S')" /space/log/server.log  | grep 'ERROR'

However nothing is grepped! Can you help me to fix it ? Thanks!

然而,什么都没有得到!你能帮我修一下吗?谢谢!

回答by Krzysztof Krasoń

You need quotes around the -1 hourand also you want to remove the seconds and minutes from the output (your current solution finds data only for the first second 1 hour ago):

您需要引号,-1 hour并且您还想从输出中删除秒和分钟(您当前的解决方案仅查找 1 小时前第一秒的数据):

grep "^$(date -d '-1 hour' +'%H')" /space/log/server.log  | grep 'ERROR'

回答by Esa Lindqvist

grep -E "^($(date -d '-1 hour' '+%H')|$(date '+%H')):[0-9]{2}:[0-9]{2}" /space/log/server.log | grep 'ERROR'

Let's take a look at the parts

我们来看看零件

grep -Etells grep to use extended regular expressions (so we don't need to escape all those brackets)

grep -E告诉 grep 使用扩展的正则表达式(所以我们不需要转义所有这些括号)

date -d '-1 hour' '+%H'prints the previous hour. Similarly date '+%H'prints the current hour. These need to be evaluated at runtime and captured in a capture group, that's why we have the (date|date)structure (you'll probably want some data not only from the previous hour, but the current running hour).

date -d '-1 hour' '+%H'打印前一小时。同样date '+%H'打印当前小时。这些需要在运行时评估并在捕获组中捕获,这就是我们拥有(date|date)结构的原因(您可能不仅需要前一小时的数据,还需要当前运行小时的数据)。

Next you need to specify that you are indeed looking at timestamps. We use :to delimit hours, minutes and seconds. A two-digit number group can be matched with the [0-9]{2}regexp (this is basically identical to [0-9][0-9]but shorter)

接下来,您需要指定您确实在查看时间戳。我们:用来分隔小时、分钟和秒。可以用正则[0-9]{2}表达式匹配一个两位数的数字组(这个基本相同[0-9][0-9]但更短)

There you go.

你去吧。

Ps. I'd recommend sed.

附言。我推荐sed。