Home > Mobile >  output the line contained in the file by keyword using perl
output the line contained in the file by keyword using perl

Time:10-29

I have a file aa.txt:

John Norman
Robert Anson
Christopher Fowler
Robert Harris
Dan Simmons

I want to enter keywords from the keyboard and check them in the file element by line. If true, output the entire line containing that keyword. For example, if I enter the word "John", it will output "John Norman" How do I write perl script? Thanks you very much!

CodePudding user response:

I think you want grep:

grep John aa.txt

You can also do it case-insensitively:

grep -i John aa.txt

But let's say that you want multiple searches in one go. The first thing to figure out, and which your question doesn't provide, is the mechanism you desire. So, I'll have the first argument be the file and the rest be the things to find:

% ./some_script file_to_search.txt key1 ...

Then it's pretty simple.

#!perl

my @keys = @ARGV;
@ARGV = shift @keys;

my $pattern = join '|', map { quotemeta } @keys;
my $compiled_re = qr/$pattern/;

while( <<>> ) {
    print if /$compiled_re/;
    }

Beyond that, you'd have to tell us much more about what you are trying to do.

$ perl greppy.pl aa.txt John
John Norman
$ perl greppy.pl aa.txt John Robert
John Norman
Robert Anson
Robert Harris

CodePudding user response:

This doesn't seem like a perl question at all. You can just do something like:

$ while read name; do grep -F "$name" aa.txt; done
John
John Norman
Christopher
Christopher Fowler

(In the above, every odd numbered line was entered by the user)

I suppose you could do it with:

perl -nE 'chop; open my $f, "<", "aa.txt"; while($a = <$f>) {print $a if( $a =~ $_ )}'

But note that either of these solutions is unusual. Rather than "enter keywords from the keyboard", it would be more typical to pass the search terms as arguments to grep, or to put them all in a file. The search can be greatly optimized if you only read the file once, and the solutions presented here are only useful if you really want to do this interactively for each search term. Even then, it would be more natural to just invoke grep for each term, or write a shell function to simplify the interface.

  • Related