使用perl从文件中提取数据
extracting data from a file using perl
在 Shell 脚本中使用 Perl,我试图从名为 "Fruit.txt" 的文本文件中提取单词 "apple"(该文件包含不同水果的名称)
为此我创建了一个脚本如下:
#!/usr/bin/perl
$t = 'cat Fruit.txt';
我现在如何使用 grep -o 从该文件中提取子字符串(在本例中为 apple)。谢谢
正道:
#!/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;
或:
#!/usr/bin/perl
use strict; use warnings;
while (<>) {
print if /Apple/i;
}
用法:
./script.pl Fruits.txt
或者更简洁的方式:
perl -ne 'print if /whatever/' file
你似乎尝试过的糟糕方法(不可移植):
my $file = qx(cat Fruits.txt);
或
my $file = `cat Fruits.txt`;
~ ~
注意反引号
# 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 !\n" if $t =~ /^fruit=(.+)/;
我建议阅读 perlrequick 以了解有关正则表达式的更多信息。
Perl 行命令"ultra lazy" 技巧:
perl -e 'while(<>){print "\n$_\n" if $_ =~ /whatever/}' <FILE_PATH>
:V
在 Shell 脚本中使用 Perl,我试图从名为 "Fruit.txt" 的文本文件中提取单词 "apple"(该文件包含不同水果的名称)
为此我创建了一个脚本如下:
#!/usr/bin/perl
$t = 'cat Fruit.txt';
我现在如何使用 grep -o 从该文件中提取子字符串(在本例中为 apple)。谢谢
正道:
#!/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;
或:
#!/usr/bin/perl
use strict; use warnings;
while (<>) {
print if /Apple/i;
}
用法:
./script.pl Fruits.txt
或者更简洁的方式:
perl -ne 'print if /whatever/' file
你似乎尝试过的糟糕方法(不可移植):
my $file = qx(cat Fruits.txt);
或
my $file = `cat Fruits.txt`;
~ ~
注意反引号
# 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 !\n" if $t =~ /^fruit=(.+)/;
我建议阅读 perlrequick 以了解有关正则表达式的更多信息。
Perl 行命令"ultra lazy" 技巧:
perl -e 'while(<>){print "\n$_\n" if $_ =~ /whatever/}' <FILE_PATH>
:V