[X-Unix] Question about grep

Brian Medley bpm-list-osx-unix at 4321.tv
Tue Mar 16 18:09:31 PST 2004


On Tue, Mar 16, 2004 at 07:02:59PM -0500, Our Pal Al wrote:

> So in a file with lots of lines like this -
> 
> 3/15/2004    5:58 PM    Drogo-OS X (21.177)    Macintosh HD    -24001
> user canceled    0:34:00    129.85.21.177
> 
> How can I formulate grep to grab on the mm/dd/yyyy field and pull out "any
> lines where the date is no older than 7 days ago"?

I made a stab at doing this in perl.  It includes the filtering
of lines with Successful in them.  To understand what is going on
requires a bit of perl knowledge that I won't go over now, but if
you have specific questions, feel free to ask.

$ cat date_grabber.txt
2/3/2004    5:58 PM    Drogo-OS X (21.177)
3/1/2004    5:58 PM    Drogo-OS X (21.177)
3/11/2004    5:58 PM    Drogo-OS X (21.177) Successful
3/12/2004    5:58 PM    Drogo-OS X (21.177)
3/13/2004    5:58 PM    Drogo-OS X (21.177)
3/14/2004    5:58 PM    Drogo-OS X (21.177)
3/15/2004    5:58 PM    Drogo-OS X (21.177) Successful
3/16/2004    5:58 PM    Drogo-OS X (21.177)
$ ./date_grabber.pl < date_grabber.txt 
3/12/2004    5:58 PM    Drogo-OS X (21.177)
3/13/2004    5:58 PM    Drogo-OS X (21.177)
3/14/2004    5:58 PM    Drogo-OS X (21.177)
3/16/2004    5:58 PM    Drogo-OS X (21.177)
$ cat date_grabber.pl
#! /usr/bin/perl

use strict;
use warnings;

use POSIX qw(strftime);

my $time = time;
my %allowed_dates;

# setup our allowed date range.
foreach (0 .. 7) {
    my $date = &strftime("%m/%d/%Y", localtime $time);
    $allowed_dates{$date} = 1;
    $time -= 86_400;
}

while (<STDIN>) {
    # should be the same as grep -v Successful
    next if /Successful/;

    # try and parse out a date.  quit processing if none is found.
    unless ($_ =~ m#(\d+)/(\d+)/(\d+)#) {
        die "Invalid line found: $_";
    }

    # make the day and month "right-justified" with zeros
    my $date = sprintf("%02d/%02d/%4d", $1, $2, $3);

    # skip lines that don't match our criteria from above
    next unless $allowed_dates{$date};

    print;
}
$

-- 
~`^`'~=-._.-=~'`^`'~=-._.-=~'^'~=-., \|/  (___)  \|/ _,.-=~'`^`
                                      @~./'O o`\.~@
      "Knowledge is Power"           /__( \___/ )__\  *PPPFFBT!*
         -- Francis Bacon               `\__`U_/'
 _.-=~'``'~=-._.-=~'``'~=-._.-=~'`^`'~= <____|'  ^^`'~=-.,__,.-=
~'^`'~=-._.-=~'`^`'~=-._.-=~'^'~=-.,__,.-==--^'~=-.,__,.-=~'`^`



More information about the X-Unix mailing list