Saravanan Murugaiah wrote:
Dear All,
Hello,
I want to search a particular word in some set of files, which are kept in
a directory. In this, I want to display the search result in some other out
file like including the line number with file name, etc. For example, if I
want to search the word "Good Try" in all the files in a directory, then
the output should be stored in some "result.out" file which contains
"File1.txt" contains the searchable word "Good Try" at the line number 20.
In this, I've written the below script, in this upto search level working
fine but don't know, how to keep the result in some other file. Can you
please help me in this regard?
### Scripts start###
#!/usr/bin/perl -w
use strict;
use integer;
use File::Basename;
my $find = "Good Try";
Since this will be used as a regular expression it should probably be
compiled here:
my $find = qr/Good Try/i;
And shouldn't this be a command line option?
And I noticed in your sample file that the phrase 'Good Try' is not
present but the phrase 'Good Start' is present.
@ARGV = ('.') unless @ARGV;
my ($File, $Dir, $Ext) = fileparse($ARGV[0], qr{\..*});
I don't understand. Are you passing in a file name that has to be
parsed? Or are you just passing in a single directory name, and if so,
why are you parsing it?
print "Searching in '$Dir'\n";
opendir(DIR, $Dir) or die "\nCan't opendir $Dir: $!.";
my @files = grep (/\.tex$/i, readdir(DIR));
Your enclosed sample file 'file1.txt' has a '.txt' extension but here
you are testing for a '.tex' extension? And shouldn't this be a command
line option?
closedir(DIR);
foreach my $file (@files)
{
my $c = 0;
my $myFile = $Dir . "\\". $file;
open (FILE, "<$myFile") or die $!;
for (<FILE>)
It would be better to use a while loop. A for loop has to read the
entire file into memory in order to process it as a list.
Also, I noticed in your sample file that one instance of the phrase
'Good Start' is separated by a newline so this method will not count that.
{
if ($_ =~ /$find/i)
{
$c = $c + 1;
}
}
print $file . "\n" if ($c> 0);
You said you wanted to display the line number. If you had used a while
loop then the current line number would be in the $. variable.
close(FILE);
}
exit(0);
###end of script###
I've attached a sample file also with this mail. Your helps are highly
appreciated.
John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction. -- Albert Einstein
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/