#!/usr/bin/perl use strict; use warnings; my $emailNum; $/ = ''; # Set readline to "Paragraph mode" while () { if (!$emailNum || /^From:/im) { ++$emailNum; print "---- Email $emailNum\n"; } print; } __DATA__ From: here To: there Data: I have a number of e-mail messages (envelope, headers, body, sometimes including base64-encoded attachments) which are spread out among an arbitrary number of text files. In most cases, there are multiple messages in each text file. I want to subset each large file so that each e-mail is saved to its own file. So, if the source file is "mails.txt" containing three messages, I want to create (e.g.) mails_000001.txt, mails_000002.txt, and mails_000003.txt. From: somewhere To: elsewhere Data: A second email #### ---- Email 1 From: here To: there Data: I have a number of e-mail messages (envelope, headers, body, sometimes including base64-encoded attachments) which are spread out among an arbitrary number of text files. In most cases, there are multiple messages in each text file. I want to subset each large file so that each e-mail is saved to its own file. So, if the source file is "mails.txt" containing three messages, I want to create (e.g.) mails_000001.txt, mails_000002.txt, and mails_000003.txt. ---- Email 2 From: somewhere To: elsewhere Data: A second email