[英]extracting data from a file using perl
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) 在Shell脚本中使用Perl,我试图从名为“ Fruit.txt”的文本文件中提取单词“ apple”(该文件包含不同水果的名称)
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. 现在如何使用grep-o从该文件中提取子字符串(在这种情况下为apple)。 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. 我建议阅读perlrequick ,以获取有关正则表达式的更多信息。
Perl line command "ultra lazy" trick: Perl行命令“超懒”的把戏:
perl -e 'while(<>){print "\n$_\n" if $_ =~ /whatever/}' <FILE_PATH>
:V :V
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.