Extract email address from a text file
Last Updated on Thursday, 12 August 2010 13:07 Thursday, 12 August 2010 12:42
A following perl script and regular expression extracts all email addresses from an given text file. Sample text:
This perl script extracts all email addresses from an given text file. This email address is valid: web@email.net and this email address is not valid web@email. Same as what_ever@public.com is a valid email address and address test@test. is not valid !
Regular expression to extract an email address using perl:
#!/usr/bin/perl
use strict;
my $email_count;
while (my $line = <>) { #read from file or STDIN
foreach my $email (split /\s+/, $line) {
if ( $email =~ /^[-\w.]+@([a-z0-9][a-z-0-9]+\.)+[a-z]{2,4}$/i ) {
print $email . "\n";
$email_count++;
}
}
}
print "Emails Extracted: $email_count\n";
Execution:
$ ./extract_email.pl emails.txt web@email.net what_ever@public.com emails Extracted: 2















