如何通过日期时间范围到grep? [英] how to grep by date time range?

查看:716
本文介绍了如何通过日期时间范围到grep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志文件如下:

I have a log file looks like:

2011-03-21 00:01 xxxx
2011-03-22 04:05 xxxx
....
2011-03-25 10:12 xxxx
....
2011-04-04 12:23 xxxx

我想有这需要2个参数的日期范围,脚本,例如:

I want to have a script which requires 2 arguments as the date range, for example:

grep-date-range.sh 2011-03-25 2011-04-02

它会发现在[2011-03-25,2011-04-02]所有日志。我知道一个特定的情况下,我可以使用通配符,但它不是一般的在我看来。可能有人给我一个解决方案吗?

It will find all logs in [2011-03-25, 2011-04-02]. I know for a specific case i can use wildcard, but it's not general in my opinion. Could someone give me a solution?

编辑:
Python脚本也可以接受。

Python script is also acceptable.

推荐答案

他的是它可以更好地写一个简短的Python脚本的情况。在thelanguage高层次日期操作功能可以派上用场了。

his is a case where it may be better to write a short Python script. The high level date manipulations capabilities in thelanguage can be handy.

脚本波纹管是非常简单 - 多一点工作,它可以照顾本地时间的​​差异,夏令时间,等等。

The script bellow is very simple - with a bit more work it could take care of localtime differences, Daylight saving time, and so on.

#! /usr/bin/python
import sys
from datetime import datetime
d_format = "%Y-%m-%d"

try:
    start = datetime.strptime(sys.argv[1], d_format)
    end = datetime.strptime(sys.argv[2], d_format) 
except (TypeError, IndexError):
    sys.stderr.write("Example: grep-date-range.py 2011-03-25 2011-04-02 \n")

for line in sys.stdin:
    try:
        date = datetime.strptime(line.split()[0], d_format)
        # suit the <=, <, comparisons bellow to your needs:
        if start <= date < end:
            sys.stdout.write(line)
    except (ValueError, IndexError):
        pass 

这篇关于如何通过日期时间范围到grep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆