Some Computer Hints


Perl Script - Grep

This script is a simple version of the UNIX grep command and is similar to the Windows find command. It will search lines in files for a specific regular expression. The standard UNIX grep switches (-i: ignore case; -v: display not matching lines) are supported.

#!/usr/bin/perl
# grep.pl - Simulate UNIX grep command.
# Fedon Kadifeli, 1998 - April 2003.

$opt = shift;
if ($opt =~ s/^\-//) {
  $re = shift;
} else {
  $re = $opt;
  $opt = "";
}
die "Usage: grep.pl [-iv] regexp [files]\n" if ! defined $re;
$igncase = ($opt =~ s/i//g);
$nomatch = ($opt =~ s/v//g);
die "Unknown option `$opt'\n" if $opt ne "";
@ARGV = ("-") if $#ARGV < 0;
for $fn1 (@ARGV) {
 for $fn (glob $fn1) {
  if (open FH, "<$fn") {
    $pref = $fn eq "-" ? "" : "$fn:";
    if ($igncase) {
      while (<FH>) {
        print  "$pref$.:$_" if (/$re/i) xor $nomatch;
      }
    } else {
      while (<FH>) {
        print  "$pref$.:$_" if (/$re/) xor $nomatch;
      }
    }
    close FH;
  }
 }
}