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: This email address is being protected from spambots. You need JavaScript enabled to view it. and this email address
is not valid web@email. Same as This email address is being protected from spambots. You need JavaScript enabled to view it. 
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
This email address is being protected from spambots. You need JavaScript enabled to view it.
This email address is being protected from spambots. You need JavaScript enabled to view it.
emails Extracted: 2


Go to top