Subject: Re: Repalcement for grep(1)
To: Jamie Howard <howardjp@wam.umd.edu>
From: Dag-Erling Smorgrav <des@flood.ping.uio.no>
List: tech-userlevel
Date: 07/04/1999 14:09:47
Jamie Howard <howardjp@wam.umd.edu> writes:
> I made the version in FreeBSD 4.0 my target except for -A num, -B num, -C,
> -num, and -Z.  These are not required by the Single Unix Specification or
> POSIX and I felt they would bloat my code too significantly.  

I find those quite useful, and I don't see how they'd bloat your code
a lot. You need a line @queue and a $toprint counter, as well as $lead
and $trail counters. $regexp is the expression to search for, and
$line is a scratch variable. Initialize by setting $lead to the -A
argument, $trail to the -B argument; if you encounter -C, set $lead
and $trail to 2; if you encounter -<num>, set $lead and $trail to
<num>. Now for the search algorithm in Perl:

$toprint = 0;
@queue = qw();

while ($line = <INPUT>) {
    if ($toprint) {
        print $line;
        --$toprint;
    } else {
        shift @queue if (@queue > $lead);
        push @queue, $line;
    }
    next unless ($line ~ m/$regexp/o);
    while (@queue) {
        print shift @queue;
    }
    $toprint = $trail;
}

This should be trivial to translate to C. The only non-trivial part of
implementing this stuff is that you have to trick getopt() to make
-<num> work. You'll have to put a : at the start of your getopt()
string and examine every argument getopt() complains about.

Hope this helps... keep up the good work!

DES
-- 
Dag-Erling Smorgrav - des@flood.ping.uio.no