Possible Duplicate:
How can I implement Unix grep in Perl?
Is there anyway I can write a perl script to print out all lines in a file that co开发者_开发知识库ntains the string input by the user?
There are two separate concepts in this answer:
- File IO, and iterating through all lines in a while
- Regular expression, and especially passing a variable to a regular expression.
Note the use of quotemeta. It is important when the user input contains RE specific characters (which may even create an illigel RE if you don't handle it).
Here is the code:
print "Looking for: ";
my $input = <>;
chomp $input;
my $re = quotemeta $input;
open my $fh, "<", "myfile.txt" or die $!;
while( <$fh> ) {
print if /$re/;
}
close $fh;
You add the regular expression modifer "i"
print "Name: ";
my $string = <>;
open FILE, "test.txt" or die $!;
while(<FILE>) {
chomp;
print "$_\n" if(/$string*/i);
}
close FILE;
Oh, figured out how to do it. Turned out to be quite simple But how do I do it if I don't want the search to be case sensitive?
print "Name: ";
my $string = <>;
open FILE, "test.txt" or die $!;
while(<FILE>) {
chomp;
print "$_\n" if(/$string*/);
}
close FILE;
Your while loop body is a bit complex. This also works:
while (<FILE>) { print if /$string/i }
There's no need to chomp the newline and then add it back in.
One liner:
perl -nE 'BEGIN{$pattern=shift};say if /$pattern/i' pattern filename(s)
or
perl -nE 'BEGIN{$pattern=shift};say "$ARGV $.: $_" if /$pattern/i' pattern filename(s)
to get the file and line number too.
精彩评论