Extract a record containing a specific time from the log

This is an example to extract a record containing a specific time.

use strict;
use warnings;

print "(1) Extract a record containing a specific range of time.\n";
my @records = (
  '1 7:00:00 aaa',
  '2 8:00:00 iii',
  '3 9:00:00 uuu',
  '4 10:00:00 eee',
  '5 11:00:00 ooo',
);

my $start_time = '08:00:00';

# This time is not included
my $end_time = '11:00:00';

for my $record(@records) {
  
  # Extract the time
  if ($record =~ /(\d{1,2}): (\d{2}) :(\d{2})/) {
    # You can compare as a string by matching the format.
    # '7: 00:00'->'07:00:00'
    my $time = sprintf("%02s:%02s:%02s", $1, $2, $3);
    
    # Extract the records included from the start time to the end time.
    if ($time ge $start_time && $time lt $end_time) {
      print $record . "\n";
    }
  }
}

Output

(1) Extract a record that includes a specific range of time.
2 8:00:00 iii
3 9:00:00 uuu
4 10:00:00 eee

Explanation

Adjust the time format

Use the sprintf function to format the time. By adjusting the length of the string to the same length, it is possible to compare with the string.

if ($record =~ /(\d{1,2}): (\d{2}) :(\d{2})/) {
  my $time = sprintf("%02s:%02s:%02s", $1, $2, $3);
  
  if ($time ge $start_time && $time lt $end_time) {
    print $record . "\n";
  }
}

Extract the records included from the start time to the end time

ge and lt are operators that compare which comes first in the dictionary order of strings. ge is an abbreviation for greater than or equel and lt is an abbreviation for lower than.

if ($time ge $start_time && $time lt $end_time) {
  print $record . "\n";
}

Perl Reverse Dictionary/To Date and Time

Related Informatrion