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:  and this email address
is not valid web@email. Same as  
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


emails Extracted: 2

Free Linux eBooks

Do you have the right skills?

Our IT Skills Watch page reflects an up to date IT skills demand leaning towards the Linux and Unix environment. We have considered a number of skills and operating systems.

See the result...

Linux Online Training

Learn to run Linux servers and prepare for LPI certification with Linux Academy. 104 available video lessons with PDF course notes with your own server!

Go to top