Quantcast
Viewing latest article 1
Browse Latest Browse All 3

Answer by Matthieu Moy for Would GREP work to filter a log file based on keywords, dates, timestamps? Or is there a better alternative?

grep filters regular expressions. It is very good at filtering lines containing one particular keyword, but a date range is hard to specify using regular expressions. For example, to get errors between Jan 1st, 20:00 and Jan 3rd, 2:00, you have to accept all times for Jan 2nd, but only evening for Jan 1st and only early morning for Jan 3rd. You can't separate time of day and date, for example.

It is much simpler to use a more expressive tool that can natively compare dates. Perl is a popular language to do this kind of things, and Python is a good alternative.

Here's an example in Python:

import re
import time

f = open('/var/log/syslog')
line = f.readline()
while line:
    # Get the date at the beginning of line with a regex
    m = re.match(r'^([^\s]+\s+[^\s]+\s+[^\s]+)\s+', line)
    # Parse the date
    date = time.strptime(m.group(1), '%b %d %H:%M:%S')
    # Compare with a given date
    if date > time.strptime('Jun 6 14:00:00', '%b %d %H:%M:%S'):
        print(line, end='')

    # Read next line
    line = f.readline()

Viewing latest article 1
Browse Latest Browse All 3

Trending Articles