我希望在Perl中迭代一个文件,如果它找到一个特定的单词,则存储与特定模式匹配的行后面的其他行。ldap.txt文件在几个Gigs中都非常大。
user.txt
test1
game ldap.txt
dn: uid=test1,ou=people,dc=admin,dc=local
blah
blah
maillocaladdress: test1@example.com
maillocaladdress: test.team@example.com
maillocaladdress: test11@example.com
some date
some more data
data
dn: uid=game,ou=people,dc=admin,dc=local
blah
blah
maillocaladdress: game@example.com
maillocaladdress: game.test@example.com
maillocaladdress: game-test@example.com
some date
some more data
data 以此类推..
打开user.txt,遍历每个用户,检查dn: ldap.txt中的每一行。如果匹配,则将与maillocaladdress匹配的所有行的值存储到varialbe,我假设是在散列键/值pari中,但这里的值不止一个。
例如:
test1 matches dn: uid=test1,ou=people,dc=admin,dc=local 为每个用户存储以下值。
test1@example.com
test.team@example.com
test11@example.com 代码
#! /usr/bin/perl
use strict;
use warnings;
my $ldiffile = shift;
my %emails;
open my $US, '<', 'users2.txt'
or die "Could not Open the file users2.txt: $!";
open my $FH, '<', $ldiffile
or die "Could not Open the file $ldiffile: $!";
chomp(my @users = <$US>);
#print "@users \n";
foreach my $uid (@users) {
print "$uid \n";
# while ( chomp(my $line = <$FH>) ) {
while (my $line = <$FH>) {
chomp ($line);
if ( $line =~ /dn: uid=$uid,ou=People,dc=admin,dc=local/i ) {
print "$line \n";
if ( $line =~ /mailLocalAddress: ([\w\.\-\_\@]+)/ ) {
print "<<<< $line >>>> \n";
push ( @{$emails{$uid}}, $1 );
}
}
}
}发布于 2014-03-25 06:07:13
您的程序中可能存在一些缺陷。您试图遍历每个@users的文件,但实际上只是循环遍历第一个用户的文件。
相反,您应该做的是循环遍历文件,提取userid,并将它们与您的已接受用户列表进行匹配。以下代码应该可以执行您想要的操作:
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
open my $US, '<', 'users2.txt';
chomp(my @users = <$US>);
close $US;
my %isuser = map {$_ => 1} @users;
my %emails;
my $userid = '';
while (<>) {
chomp;
if (/^dn: uid=([^,]*)/) {
$userid = $1;
$userid = '' if !/,ou=People,dc=admin,dc=local/;
} elsif ($isuser{$userid}) {
if (/mailLocalAddress: ([\w.-_@]+)/i) {
print "$userid - <<<< $_ >>>> \n";
push @{$emails{$userid}}, $1;
}
}
}此外,测试mailLocalAddress的正则表达式有大写字母,而示例数据没有大写字母。因此,在正则表达式上放置一个/i标志。
https://stackoverflow.com/questions/22621267
复制相似问题