Email lists > > [Perl] Re: How to search particular words in a file > [Perl] Re: How to search particular words in a file

[Perl] Re: How to search particular words in a file




This post if a part of  this thread

2007-09-08 12:07:34
Re: How to search particular words in a file

Avinash,

Here's one solution.

Darren

====

#!/bin/perl/bin

###
### title: pgrep
### author: darren miller
###
### perl alternative to UNIX grep command,
### which searches for patterns in a file.
### exhanced version of the program by the same
### name in the camel book from O'Reilly.
###
### usage: pgrep -i -e "html" -e "form" *.html *.htm
###
### -i = ignore case
### -e = identifies a regular expression to search for
###

my expressions; # array of regular expressions to search for
my fileglobs; # array of filename patterns to search in
my $ignorecase="false"; # ignore case?

while ($param = shift(ARGV)) {
if ($param eq "-e") {
push expressions, shift(ARGV);
} elsif ($param eq "-i") {
$ignorecase = "true";
} else {
push fileglobs, $param;
}
}

foreach $fglob (shift(fileglobs)) { # loop
through file name patterns
foreach $f (glob($fglob)) { # loop
through files that match the current pattern
if (open FH, "<$f") { # open
the file
my $line=0; #
initialize a line counter
while (<FH>;) { # loop
through the current file
$line++; #
increment counter
foreach $expression (expressions) { # loop
through expressions
if ((m/$expression/) or ($ignorecase eq "true" and m/
$expression/i)) { # check for a match
printf "%s (%.6d): %s", $f, $line, $_; # print
the file name, line number, and line
}
}
}
}
}
}

--- In Perl_Official%40yahoogroups.com">Perl_Officialyahoogroups.com, avinash k <avik1612...> wrote:
&gt;
> hi,
>
> I am trying to find particular words in text files(i.e. *.txt
files)
>
> Should i use regular expressions in doing?
&gt;
> Thanks in advance
> Avinash

__._,_.___
.

__,_._,___

about | contact  Other archives ( Real Estate discussion Medical topics )