I suppose I'd do it like this;
#!/usr/bin/perl
use strict;
use warnings;
my $filename = "C:/FolderA/test.txt"; # default input file
if ( @ARGV > 1 and -f $ARGV[1] ) {
$filename = pop; # alternatively, get input file from command lin
+e
}
my $pattern;
if ( @ARGV ) {
$pattern = shift; # get search pattern from command line
}
else {
die "Usage: $0 search_pattern_regex [input.filename]\n";
}
open( FILE, "<", $filename ) or die "Open failed on $filename: $!";
my @line_buffer;
while (<FILE>) {
push @line_buffer, $_;
shift @line_buffer if ( @line_buffer > 3 );
print join( "", @line_buffer, "\n" )
if ( @line_buffer > 1 and $line_buffer[-2] =~ /$pattern/ );
}
print join( "", @line_buffer ) if ( $line_buffer[-1] =~ /$pattern/ );
close FILE;
Some points to consider:
- How do you want to handle the case where two consecutive lines match the pattern?
- Do you want to enable or disable the use of regex magic characters in the user-supplied pattern?
- Do you want to parameterize the number of lines of context to include in the output for each match (providing a command line option to control this)?
Note that the gnu "grep" tool (available for windows via cygwin and other "unix-utils-for-windows" packages) already does what you are trying to do here, so unless there's some perlish capability you want to add that the standard gnu grep doesn't have, there's no need to reinvent this wheel.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.