add proper error handling for all final exec calls
[hband-tools.git] / user-tools / grepdatetime
blobb8598e528a6be90e691dec8c9c7eb74090bf7fb1
1 #!/usr/bin/env perl
3 use Date::Parse;
4 use Getopt::Long;
5 use feature qw/switch/;
6 use POSIX qw/strftime/;
8 $print_unparsed = 0;
9 $prefix_filename = 0;
11 sub prnt
13 my ($fname, $_) = @_;
14 if($prefix_filename)
16 print "$fname:";
18 print;
21 Getopt::Long::Configure(qw/no_ignore_case/);
22 GetOptions(
23 'f|from=s' => \$dt_from,
24 't|to|till=s' => \$dt_till,
25 'r|match-date=s' => \$re_match_date,
26 'u|print-unparsed!' => \$print_unparsed,
27 'p|prefix-filename!' => \$prefix_filename,
28 ) or
29 die "Usage: $0 -f FROM -t TO [-r | -u] [FILES]";
31 $ts_from = defined $dt_from ? str2time($dt_from) : undef;
32 $ts_till = defined $dt_till ? str2time($dt_till) : undef;
33 $re_match_date = '>(\S+\s+\S+\s+\S+)';
35 printf STDERR "Searching from: %s\n", $ts_from ? strftime('%c', localtime $ts_from) : "ANY";
36 printf STDERR "Searching till: %s\n", $ts_till ? strftime('%c', localtime $ts_till) : "ANY";
38 for my $fname (@ARGV)
40 my ($ext) = ($fname =~ /\.([^\.]+)$/);
41 my $openmode = '-|';
42 my $decompressor;
43 my @source;
45 given($ext)
47 when('xz')
49 $decompressor = "unxz";
51 when('gz')
53 $decompressor = "gunzip";
55 default
57 $openmode = '<';
60 if(defined $decompressor)
62 @source = $decompressor, $fname;
64 else
66 @source = $fname;
68 if(open my $fh, $openmode, @source)
70 while(<$fh>)
72 my ($dt) = (m/$re_match_date/);
73 if($dt)
75 my $ts = str2time($dt);
76 if((not defined $ts_from or $ts >= $ts_from) and (not defined $ts_till or $ts <= $ts_till))
78 prnt $fname, $_;
81 elsif($print_unparsed)
83 prnt $fname, $_;
86 close $fh;
88 else
90 warn "$fname: $!\n";