Question

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 a certain domain, e.g. hacker@bad.com. I want to get rid of all email addresses that are @bad.com

Was it helpful?

Solution

Use grep instead of Perl

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

On Windows

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

OTHER TIPS

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 $_;
   }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top