#!/usr/bin/perl # # findstr - look for a regular expression within a file # # ANSI escape sequences: BOLD \e[1;39m # NORMAL \e[0;39m # GREEN \e[1;32m # RED \e[1;31m # REVERSE \e[0;7m # NORMAL \e[0;27m # $usage = "Usage: findstr [-c [-p pattern] [-f file]]\n". " -p pattern Specify regular expression to use\n". " -f file Specify file to open (\"-\" means STDIN)\n". " -r Print matches in reverse\n"; use Getopt::Std; getopts('p:f:r') or die $usage; # Process switches $pattern = ($opt_p) ? $opt_p : 'Linux'; if ($opt_f) { open(FILE,"<$opt_f") or die "ERROR: $!"; # Open input file } else { open(FILE,"<-") or die "ERROR: $!"; # Open STDIN for reading } $pre_pat = ($opt_r) ? "\e[1;7m" : ''; $post_pat = ($opt_r) ? "\e[0;27m" : ''; $ct = 0; while () { if (/$pattern/) { $ct += s/($pattern)/$pre_pat\1$post_pat/g; print; } } print "Pattern \"$pattern\" found $ct times.\n"; close(FILE);