读取文件内容并使用正则表达式在Perl中的每个文件中找到一个模式 [英] Read file content and use Regular Expression to locate a pattern in each File in Perl
本文介绍了读取文件内容并使用正则表达式在Perl中的每个文件中找到一个模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当使用notepad ++ regexp引擎时,我执行以下操作找到模式:
< div class =opacity description>(。*)< / div>
所以这是我正在寻找的模式。
这是我如何打开并列出目录中的所有文件。
my $ d = shift;
opendir(D,details /)||死不能opedir $ d:$!\\\
;
我的@list = readdir(D);
closedir(D);
foreach我的$ f(@list){
打印\ $ f = $ f\\\
;
}
解决方案
use strict;
使用警告;
使用HTML :: TreeBuilder :: XPath;
我的($ dir)= @ARGV;
我的@files = glob$ dir / *;
为我的$文件(@files){
我的$ tree = HTML :: TreeBuilder :: XPath-> new_from_file($ file);
我的@opacity = $ tree-> findnodes_as_strings('// div [@ class =opacity description]');
打印\\\
$ file\\\
;
打印$ _\\\
for @opacity;
}
I have about 200 files located in the same directory, all of which contain a specific piece of content that I need to match using RegExp and either save all of the matched contents into a single array or store them in a new file.
When working with notepad++ regexp engine I do the following to locate the pattern:
<div class="opacity description">(.*)</div>
so that is the pattern I am looking for.
And this is how i Open and List all the files in the directory.
my $d = shift;
opendir(D, "details/") || die "Can't opedir $d: $!\n";
my @list = readdir(D);
closedir(D);
foreach my $f (@list) {
print "\$f = $f\n";
}
解决方案
use strict;
use warnings;
use HTML::TreeBuilder::XPath;
my ($dir) = @ARGV;
my @files = glob "$dir/*";
for my $file (@files) {
my $tree = HTML::TreeBuilder::XPath->new_from_file($file);
my @opacity = $tree->findnodes_as_strings('//div[@class="opacity description"]');
print "\n$file\n";
print " $_\n" for @opacity;
}
这篇关于读取文件内容并使用正则表达式在Perl中的每个文件中找到一个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文