A couple of years ago I wrote an article about selecting specific time ranges from log files. I proposed two options: either convert all timestamps to epoch format (a CPU-intensive process) or rely on regex (limited to specific date/time periods). Here’s a followup with a couple more methods. Perhaps a bit more practical.

First, let talk about generating timestamps for time ranges. I always prefer examples to long-winded explanations, so here are a few.

Generate a daily range from '2018-10-02' to '2019-02-28'
Generate an hourly range from 'Oct 29 23:00:00' to 'Nov 1 23:00:00'
Generate a range from 'Apr 1 13:23:12' to 'Apr 1 13:41:02' at a 1-second interval

With that out of the way, lets take a look how to use these timestamps to select specific time ranges from log files.

Grep lines from syslog for the 'Oct 2 14:24' to 'Oct 2 14:54' period
Grep lines from syslog for the 'Oct 2 14:24:13' to 'Oct 2 14:32:13' period

Note: grep can accept a limited number of arguments. You can find out the limit by running getconf ARG_MAX. See the follow-up examples showing how to get around this limitation.

The example below is similar to the previous script. However, to avoid the grep: Argument list too long error, the list of arguments is written to a temporary file.

Another way to cut down on the size of the argument list is by using xargs. This method also allows you to utilize multiple processor cores. The downside here is that results from each xargs thread may not be in chronological order. In the following example we’re using sort command to put all log lines back in order.

 

Leave A Reply

Please enter your comment!
Please enter your name here