开发者

Perl: Getting lines from file based on user input [duplicate]

开发者 https://www.devze.com 2023-02-10 19:25 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How can I implement Unix grep in Perl?
This question already has answers here: Closed 11 years ago.

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:

  1. File IO, and iterating through all lines in a while
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号