【发布时间】:2017-02-02 18:10:12
【问题描述】:
我正在尝试从匹配*main_log 的所有文件中匹配一个名为expressions.txt 的文件中给出的关键字/文本/行。当找到匹配项时,我想为匹配的每一行打印注释。
有没有更好的打印方法?
expression.txt
Hello World ! # I want to print this comments#
Bye* #I want this to print when Bye Is match with main_log#
:::
:::
下面是我使用的代码:
{
open( my $kw, '<', 'expressions.txt' ) or die $!;
my @keywords = <$kw>;
chomp( @keywords ); # remove newlines at the end of keywords
# get list of files in current directory
my @files = grep { -f } ( <*main_log>, <*Project>, <*properties> );
# loop over each file to search keywords in
foreach my $file ( @files ) {
open( my $fh, '<', $file ) or die $!;
my @content = <$fh>;
close( $fh );
my $l = 0;
foreach my $kw ( @keywords ) {
my $search = quotemeta( $kw ); # otherwise keyword is used as regex, not literally
#$kw =~ m/\[(.*)\]/;
$kw =~ m/\((.*)\)/;
my $temp = $1;
print "$temp\n";
foreach ( @content ) { # go through every line for this keyword
$l++;
printf 'Found keyword %s in file %s, line %d:%s'.$/, $kw, $file, $l, $_ if /$search/;
}
}
}
我尝试使用此代码打印括号 (...) 中提到的 cmets,但它没有以我想要的方式打印,如下所示:
如果表达式.txt 包含
Hello World ! # I want to print this comments#
如果Hello World ! 字符串在我的名为main_log 的文件中匹配,那么它应该只匹配main_log 中的Hello World!,但打印# I want to print this comments# 作为注释以供用户理解关键字。
这些关键字可以是任意长度或包含任意字符。
虽然我在命令提示符上使用了 perl -w Test.pl > my_output.txt 命令,但对将所需的输出打印到文件中有点怀疑,但不确定如何在 perl 脚本本身内部使用
p>open( my $kw, '<', 'expressions.txt') or die $!;
my @keywords = <$kw>;
chomp(@keywords); # remove newlines at the end of keywords
# post-processing your keywords file
my $kwhashref = {
map {
/^(.*?)(#.*?#)*$/;
defined($2) ? ($1 => $2) : ( $1 => undef )
} @keywords
};
# get list of files in current directory
my @files = grep { -f } (<*main_log>,<*Project>,<*properties>);
# loop over each file to search keywords in
foreach my $file (@files) {
open(my $fh, '<', $file) or die $!;
my @content = <$fh>;
close($fh);
my $l = 0;
#foreach my $kw (@keywords) {
foreach my $kw (keys %$kwhashref) {
my $search = quotemeta($kw); # otherwise keyword is used as regex, not literally
#$kw =~ m/\[(.*)\]/;
#$kw =~ m/\#(.*)\#/;
#my $temp = $1;
#print "$temp\n";
foreach (@content) { # go through every line for this keyword
$l++;
if (/$search/)
{
# only print if comment defined
print $kwhashref->{$kw}."\n" if defined($kwhashref->{$kw}) ;
printf 'Found keyword %s in file %s, line %d:%s'.$/, $kw, $file, $l, $_
#printf '$output';
}
}
}
}
【问题讨论】:
-
还有什么问题?您是否遇到错误,或者您的代码是否执行了您不想要的操作并且您不知道为什么?请具体。您可以edit您的问题并添加详细信息。
标签: perl