Xref: utzoo comp.unix.wizards:9099 comp.unix.questions:7400
Path: utzoo!utgpu!water!watmath!clyde!bellcore!rutgers!ucsd!sdcsvax!net1!hutch
From: hutch@net1.ucsd.edu (Jim Hutchison)
Newsgroups: comp.unix.wizards,comp.unix.questions
Subject: Re: grep replacement
Message-ID: <5007@sdcsvax.UCSD.EDU>
Date: 4 Jun 88 23:37:17 GMT
References: <7882@alice.UUCP> <5630@umn-cs.cs.umn.edu> <6866@elroy.Jpl.Nasa.Gov> <4524@vdsvax.steinmetz.ge.com> <1036@cfa.cfa.harvard.EDU> <4537@vdsvax.steinmetz.ge.com>
Sender: nobody@sdcsvax.UCSD.EDU
Reply-To: hutch@net1.UUCP (Jim Hutchison)
Organization: UCSD EMU Project (Educational Microcomputer Unix)
Lines: 57

4537@vdsvax.steinmetz.ge.com, barnett@vdsvax.steinmetz.ge.com (Bruce G. Barnett)
>In <1036@cfa.cfa.harvard.EDU> wyatt@cfa.harvard.EDU (Bill Wyatt) writes:
>|
>|> There have been times when I wanted a grep that would print out the
>|> first occurrence and then stop.
>|
>|grep '(your_pattern_here)' | head -1
>
[...]
>
>Have you ever waited for a computer?  

No, never. :-)

>There are times when I want the first occurrence of a pattern without
>reading the entire (i.e. HUGE) file.

I realize this is dependent on the way in which processes sharing a
pipe act, but this is a point worth considering before we get yet
another annoying burst of "cat -v" type programs.

grep pattern file1 ... fileN | head -1

This should send grep a SIGPIPE as soon as the first line of output
trickles through the pipe.  This would result in relatively little
of the file actually being read under most Unix implementations.
I would agree that it is a bad thing to rely on the granularity of
a pipe.  Here is a sample program which can be used to show you what
I mean.

Name it grep, and use it thus wise:

% ./grep pattern * | head -1

/* ------------- Cut here --------------- */
#include 
#include 

sighandler(sig)
    int sig;
{
    if (sig == SIGPIPE)
	fprintf(stderr,"Died from a SIGPIPE\n");
    else
	fprintf(stderr,"Died from signal #%d\n", sig);
    exit(0);
}

main()
{
    signal(SIGPIPE,sighandler);
    for (;;)
	printf("pattern\n");
}
/*    Jim Hutchison   		UUCP:	{dcdwest,ucbvax}!cs!net1!hutch
		    		ARPA:	Hutch@net1.ucsd.edu
Disclaimer:  The cat agreed that it would be o.k. to say these things.  */