The first place to look is glob, since it appears that you don't want to recurse down a directory tree. As an example (NOT TESTED)
Warning! Code is NOT tested, and I won't even guarantee it will compile. Doubtless there are better ways to do this than my example. One obvious improvement could be to slurp up the entire file into a scalar, not read it into an array, by setting $/ to undef; this is probably faster. Other improvements would be to permit regex.# insert appropriate shebang line use strict; use warnings; my @files = glob("chat/*.htm"); # use something like [Hh][Tt][Mm] if y +ou're unsure about the case @files = grep { -s $_ and -f _ and -r _} @list; print "Enter search string :"; my $string = <>; # read from STDIN chomp($string); # strip off the line feed resulting from <enter> my $quoted_string = quotemeta($string); # quote all meta-characters. + Remove if not needed foreach my $file (@files) { my $filehandle; unless(open($filehandle, "<", $file)) { warn "Could not open $file because $!\n"; next; } my @contents = <$filehandle>; # presuming the files are not too la +rge chomp(@contents); close($filehandle) or die "Could't close $file because $!\n"; @contents = grep { /$quoted_string/ } @contents; if(@contents){ print "$string was found in $file:\n\t",join("\n\t",@contents), +"\n"; } }
In reply to Re: How to search string in all files in directory
by swampyankee
in thread How to search string in all files in directory
by oh5yw
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |