Perl is cool

Let’s say you work for a company that deals in email and need to look through giant mbox-format files for things. This might be hard, but with a very short perl script, you can make it easy…

#!/usr/bin/perl -w
# mboxgrep pattern file [file...]

my $pattern = shift;

my @message = ();
while (<>) {
    # Look for mbox border
    if (/^From /) {
        # Print message if pattern found
        print @message if (grep(/$pattern/, @message));
        @message = (); # Reset message
    }

    push @message, $_;
}

See! In very few lines you have a program that works like grep but works on a per-message basis. Redirect the output to a file, and you have a valid, new mbox containing messages that matched the pattern.