在指定的时间范围内从日志文件中提取数据 [英] Extract data from log file in specified range of time
问题描述
我想根据时间范围使用 shell 脚本 (bash) 从日志文件中提取信息.日志文件中的一行如下所示:
I want to extract information from a log file using a shell script (bash) based on time range. A line in the log file looks like this:
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET / HTTP/1.1" 200 123 "" "Mozilla/5.0 (compatible; Konqueror/2.2.2-2; Linux)"
我想提取数据的特定间隔.例如,我只需要从最后记录的数据中查看最近 X 分钟或 X 天前发生的事件.我是 shell 脚本的新手,但我尝试过使用 grep 命令.
i want to extract data specific intervals. For example I need to look only at the events which happened during the last X minutes or X days ago from the last recorded data. I'm new in shell scripting but i have tried to use grep command.
推荐答案
你可以使用 sed
来解决这个问题.例如:
You can use sed
for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
工作原理
-n
开关告诉 sed 不要输出它读取的文件的每一行(默认行为).
How it works
The -n
switch tells sed to not output each line of the file it reads (default behaviour).
正则表达式之后的最后一个 p
告诉它打印与前面的表达式匹配的行.
The last p
after the regular expressions tells it to print lines that match the preceding expression.
表达式 '/pattern1/,/pattern2/'
将打印第一个模式和第二个模式之间的所有内容.在这种情况下,它将打印在字符串 Feb 23 13:55
和字符串 Feb 23 14:00
之间找到的每一行.
The expression '/pattern1/,/pattern2/'
will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55
and the string Feb 23 14:00
.
这篇关于在指定的时间范围内从日志文件中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!