【问题标题】:filter a log file data from a certain time range过滤某个时间范围内的日志文件数据
【发布时间】:2018-06-22 21:29:39
【问题描述】:

我想编写一个脚本,询问用户我们想要过滤日志数据的时间间隔的第一个和最后一个日期和时间,我需要一些帮助。

我不知道如何真正找到该范围内的数据,因为我不能使用单个正则表达式。

我的日志文件如下所示:

108.162.221.147 - - [04/Aug/2016:18:59:59 +0200] "GET / HTTP/1.1" 200 10254 "-"...
141.101.99.235 - - [04/Aug/2016:19:00:00 +0200] "GET / HTTP/1.1" 200 10255 ...
108.162.242.219 - - [04/Aug/2016:19:00:00 +0200] "GET / HTTP/1.1" 200 10255...
185.63.252.237 - - [04/Aug/2016:19:00:00 +0200] "CONNECT...
108.162.221.147 - - [04/Aug/2016:19:00:00 +0200] "GET /?...
185.63.252.237 - - [04/Aug/2016:19:00:01 +0200] "CONNECT....
etc...

我的脚本:

#!/bin/bash
echo "enter the log file name  "
read fname

echo "enter the start date and time  "
read startdate

echo "enter the end fate and time  "
read enddate

result=$(some code for filtering rows from this range)
echo "$result" > 'log_results'
echo "results written into /root/log_results file"

我尝试过使用

sed -n "/"$startdate"/,/"$enddate"/p" "fname"

由于斜杠而看不到日期格式,所以没有说,正则表达式也不起作用,因为它只能从日志中找到这两个日期(也许我写错了)

我该怎么做?

【问题讨论】:

    标签: bash shell centos sh logfile


    【解决方案1】:

    通常最好使用某种专用的日志解析软件来完成此类任务,这样您就不必做自己想做的事情了。它也绝对不是正则表达式的工作。但是,如果您必须使用 grep 等文本处理工具执行此操作,我建议您采用两阶段方法:

    1. 生成要查找的每个时间戳的列表。
    2. 使用grep -F 查找日志中包含这些时间戳之一的所有行。

    例如,如果您只想找到文件的中间五行(时间戳为 [04/Aug/2016:19:00:00 +0200] 的行),这将使第 1 步变得非常简单(因为您正在生成一个单项列表,只需一个时间戳)。

    echo '[04/Aug/2016:19:00:00 +0200]' > interesting_times
    

    然后找到所有带有该时间戳的行:

    grep -F -f interesting_times logfile
    

    您可以通过降低时间戳的精度来生成更短的列表。例如查找整整两个小时的日志数据:

    echo '[04/Aug/2016:19' > interesting_times
    echo '[04/Aug/2016:20' >> interesting_times
    

    我让你来决定如何生成有趣的时间列表,但要认真研究专门构建的日志解析软件。

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 1970-01-01
      • 2017-10-30
      • 2018-08-13
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多