开发者

How can I filter email addresses that belong in a particular domain using Perl?

How can I scan through a file which contains email addresses that are separated by a new line character and get rid of those that belong to 开发者_如何学Pythona certain domain, e.g. hacker@bad.com. I want to get rid of all email addresses that are @bad.com


Use grep instead of Perl

grep -v '@bad\.com' inputfile > outputfile

On Windows

findstr /v "@bad\.com" inputfile > outputfile


Email::Address is a nice module for dealing with email addresses.

Here is an example which may whet you appetite:

use Email::Address;

my $data = 'this person email is hacker@bad.com
blah blah hacker@good.com blah blah
another@bad.com
';

my @emails      = Email::Address->parse( $data );
my @good_emails = grep { $_->host ne 'bad.com' } @emails;

say "@emails";       # => hacker@bad.com hacker@good.com another@bad.com
say "@good_emails";  # => hacker@good.com


This should do:

$badDomain = "bad.com";
while(<>)
{
        s{\s+$}{};
        print "$_\n" if(!/\@$badDomain$/);
}


The following would allow you to have a script that you can enhance in time... Instead of simply filtering out @bad.com (which you can do with a simple grep), you can write your script so you can easily sophisticate which domains are unwanted.

my $bad_addresses = {'bad.com'=>1};

while (my $s = <>) {
    print $s unless (is_bad_address($s));
}

sub is_bad_address {
    my ($addr) = @_;
    if ($addr=~/^([^@]+)\@([^@\n\r]+)$/o) {
        my $domain = lc($2);
        return 0 unless (defined $bad_addresses->{$domain});
        return $bad_addresses->{$domain};
    }
    return 1;
}


Not too different of what others have done.

use strict;
use warnings;

my @re = map { qr/@(.*\.)*\Q$_\E$/ } qw(bad.com mean.com);

while (my $line = <DATA>) {
    chomp $line;
    if (grep { $line =~ /$_/ } @re) {
        print "Rejected: $line\n";
    } else {
        print "Allowed: $line\n";
    }
}

__DATA__
good@good.com
bad@bad.com
notbad@bad.comm.com
alsobad@bad.com
othergood@good.com
not@mean.com
good@reallymean.com
bad@really.mean.com


Perl

perl -ne 'print if !/@bad\.com/' file

awk

awk '!/@bad\.com/' file 


this code should filter all the @bad.com address from the input files.

 my @array = <>;

 foreach(@array) {
   if(!/\@bad.com$/) {
     print $_;
   }
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜