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
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
# 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=(.+)/;
I recommend a read of perlrequick for more information on regular expressions.
Perl line command "ultra lazy" trick:
perl -e 'while(<>){print "\n$_\n" if $_ =~ /whatever/}' <FILE_PATH>
:V
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.