#!/usr/bin/perl # Usage: pgrep [-hin] [*] # Read man perlre(1) about Perl regular expressions. # Example1: pgrep 'm/BLAH/' *.bz2 *.gz # Example2: pgrep 'm/FOO.*BAR/i' * # Example3: pgrep 's/FOO/BAR/' * # Example4: cat * | pgrep foobar # # Note: When reading lines from STDIN it should be just cat'able, not # compressed. # Currently supports *.gz *.bz *.bz2 and normal text files. # # $Id: pgrep,v 1.3 1998/11/08 20:34:20 jlohikos Exp jlohikos $ # Author: Jouni.Lohikoski@iki.fi use Getopt::Std; &getopts('hin'); $opt_h && &usage("long"); $myKey = shift || &usage("short"); if (! ($myKey =~ m/^m.*/ || $myKey =~ m/^s.*/ || $myKey =~ m/^tr.*/ || $myKey =~ m/^y.*/) ) { $myKey = 'm/' . $myKey . '/'; } if ($opt_i) { # This is kinda messy and may not work always, use m/.../i if ($myKey =~ m/^[ms]\/.*\/[cgmosx]?[cgmosx]?[cgmosx]?[cgmosx]?[cgmosx]?[cgmosx]?$/){ $myKey .= 'i'; } else { if (! $myKey =~ m/^[ms]\/.*\/[cgmosx]*i[cgmosx]*$/) { die "pgrep: Replace -i yourself by m/blah/i\n"; } } } if ($#ARGV == -1) { @ARGV = ("STDIN"); $noFilenames = 1; } foreach $i (@ARGV) { if (defined($noFilenames)) { $bzipout = STDIN; } else { $ANYCAT = get_anycat($i); open(BZIPOUT, "$ANYCAT $i |") || die $i; $bzipout = BZIPOUT; } $linenumber = 1; while (<$bzipout>) { $was = $_; if (eval $myKey) { $is = $_; if ("$i" ne "STDIN") { print $i, ":"; } if ($opt_n) { print $linenumber, ":"; } print $is; } $linenumber++; } close ($bzipout); } sub usage { my ($mode) = @_; if ($mode ne "long") { # Are we "short" ? die "Usage: pgrep [-hin] [*]\n"; } # "long" then print STDERR "Usage: pgrep [-hin] [*]\n"; print STDERR "\t-h\tHelp. (this)\n"; print STDERR "\t-i\tCase insensitive search. Use m/blahbleh/i\n"; print STDERR "\t-n\tShow line numbers.\n"; die "\t\tRead perlre(1) (man perlre) about Perl reg.expr.\n"; } sub get_anycat { my ($filename) = @_; @a = split(m/\./, $filename); $suffix = $a[-1]; if ($suffix eq 'bz2') { $ANYCAT = `which bzip2` || die "No bzip2 in your PATH\n"; chomp $ANYCAT; $ANYCAT .= " -dc"; } elsif ($suffix eq 'bz') { $ANYCAT = `which bzip` || die "No bzip in your PATH\n"; chomp $ANYCAT; $ANYCAT .= " -dc"; } elsif ($suffix eq 'gz') { $ANYCAT = `which gzip` || die "No gzip in your PATH\n"; chomp $ANYCAT; $ANYCAT .= " -dc"; } else { $ANYCAT = `which cat` || die "No cat in your PATH\n"; chomp $ANYCAT; } return $ANYCAT; } __END__