extracting data from a file using perl

时间:2016-10-20 18:34:45

标签: regex perl gnu raspberry-pi2

Using Perl in Shell script, I am trying to extract word "apple" from a text file called "Fruit.txt"(The file holds name of different fruits)

For that I created a created a script as follow:

#!/usr/bin/perl
$t = 'cat Fruit.txt';

How can I now extract substring (in this case apple) from this file using grep - o. Thank you

3 个答案:

答案 0 :(得分:1)

The proper way :

#!/usr/bin/perl

use strict; use warnings;

my $fic = './Fruit.txt';

open my $fh, "<", $fic
    or die("An error hapenned opening file\n");

while (<$fh>) {
    print if /Apple/i;
}

close $fic;

Or :

#!/usr/bin/perl

use strict; use warnings;

while (<>) {
    print if /Apple/i;
}

Usage :

./script.pl Fruits.txt

Or the concise way:

perl -ne 'print if /whatever/' file

The bad way (non portable) that you seems to try :

my $file = qx(cat Fruits.txt);

or

my $file = `cat Fruits.txt`;
           ~              ~

Note the backticks

答案 1 :(得分:1)

# Rather than rely on the external program cat
# you can "slurp" the contents of Fruits.txt into $t.

open my $fh, "<", "Fruits.txt";
my $t = do { local $/; <$fh> };
close $fh;    


# The following is true if 'apple' appears anywhere in $t
# (it will also match 'apples', 'grappled', etc...)

if($t =~ /apple/){
    print "There is an apple!\n";
}

# If Fruits.txt is more structured, you can also do things like:    

print "There is a $1!\n" if $t =~ /^fruit=(.+)/;

我建议阅读perlrequick以获取有关正则表达式的更多信息。

答案 2 :(得分:0)

Perl line命令&#34;超懒惰&#34;特技:

perl -e 'while(<>){print "\n$_\n" if $_ =~ /whatever/}' <FILE_PATH>

:V