grep replacement (first match only per file)

J Greely jgreely at dimetrodon.cis.ohio-state.edu
Wed Jun 8 16:50:35 AEST 1988


In article <1998 at u1100a.UUCP> krohn at u1100a.UUCP (Eric Krohn) writes:
>To put in a plug for Larry Wall's perl language (Release 2.0 due soon at a
>comp.sources.unix near you):

>[suggests the following script for grep-first-only]
>perl -n -e 'if(/Subject/){print $ARGV,":",$_;close(ARGV);}' * >/dev/null

This works, and is indeed faster.  However, it shares one problem with
all of the others: '*' expansion.  As an (uncomfortable) example,
/usr/spool/news/talk/bizarre has over 2500 articles in it at our site,
and the shell can't expand that properly (SunOS 3.4, if it matters).
So, the following perl script accomplishes the same thing, no matter
how many files need searched:

#!/usr/local/bin/perl
while ($File = <*>) {
  open(file,$File);
  while (<file>) {
    if (/^Subject/){
      print $File,":",$_;
      last;
    }
  }
  close(file);
}

It's about as fast as the one-liner, and more robust.
-=-
       (jgreely at cis.ohio-state.edu; ...!att!cis.ohio-state.edu!jgreely)
		  Team Wheaties says: "Just say NO to rexd!"
	       /^Newsgroups: .*\,.*\,.*\,/h:j   /[Ww]ebber/h:j
	       /[Bb]irthright [Pp]arty/j        /[Pp]ortal/h:j



More information about the Comp.unix.wizards mailing list