如何解析电子邮件文本(bash)

时间:2015-03-07 12:09:00

标签: bash email mime quoted-printable

我有以下文字(在电子邮件中收到):

----boundary_3_f515675d-c033-4705-a01e-244d1d6c8368
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable

=0D=0ANew Lead from X Akows kl iut Sop=0D=0A=0D=0AName:=0D=0A Mic=
hael Knight=0D=0A =0D=0AEmail Address:=0D=0A <a href=3D"mailto:mi=
ck@emailaddress.co.uk">mick@emailaddress.co.uk</a>=0D=0A =0D=0ATelephon=
e:=0D=0A  00447783112974=0D=0A =0D=0AComments:=0D=0A Please send =
over more details =0D=0A=0D=0BBIOTS Reference:=0D=0A CV1614218=0D=0A=
=0D=0AYour Ref:=0D=0A 12194-109543=0D=0A=0D=0AView Property:=0D=0A=
 http://abropetisd.placudmnsdwlmn.com/CV1614218 =0D=0A=0D=0A =0D=0A=
 ----------------------------------------------------------------=
---------------=0D=0A=0D=0APlease note: You may not pass these de=
tails on to any 3rd parties.=0D=0AThis enquiry was sent to you by=
 X Akows kl iut Sop, txd UK?s #1 klsue fus kwhesena luhdsnry.  Vi=
sit www.placudmnsdwlmn.com for more information.=0D=0AQuestions? =
Email agents@placudmnsdwlmn.com=0D=0A
----boundary_3_f515675d-c033-4705-a01e-244d1d6c8368

我想解析它以获取某些信息。

我需要:

Name:
Email Address:
Telephone:
Comments:
Reference:
Your Ref:
View Property:

如何使用&#34; bash&#34;?

提取此信息

2 个答案:

答案 0 :(得分:3)

好的,我会咬人的。数据是引用可打印的,我们需要纯文本版本。所以让我们使用Perl,它已经有了代码。

#!/usr/bin/perl

use strict;
use PerlIO::via::QuotedPrint;

# Open input file through quoted-printable filter    
$ARGV[0] ne "" or die "No file specified";
open(IN, '<:via(QuotedPrint)', $ARGV[0]) or die "Could not open file";

# needles to search in the haystack.
my @needles = ( 'Name',
                'Email Address',
                'Telephone',
                'Comments',
                'Reference',
                'Your Ref',
                'View Property' );

my $line;
my $key = "";

# handle the file linewise.
foreach $line (<IN>) {

    # The data we want is always one line after the
    # key line, so:

    # If we remember a key
    if($key ne "") {
        # print key and line, reset key variable.
        print "$key =$line";
        $key = "";
    } else {
        # otherwise, see if we find a key in the current line.
        # If so, remember it so that the data in the next line
        # will be printed.
        my $n;
        foreach $n (@needles) {
            if(index($line, $n) != -1) {
                $key = $n;
                last;
            }
        }
    }
}

将此文件放入文件中,例如extract.plchmod +x,然后运行./extract.pl yourfile

答案 1 :(得分:1)

首先,谢谢大家的帮助。

我找到了另一种方法,我想在此发布。

sed -e 's/=C2=A0/ /g' abc.txt | perl -pe 'use MIME::QuotedPrint; $_=MIME::QuotedPrint::decode($_);' | grep "^Interested in:" | cut  -d' ' -f3-

sed -e 's/=C2=A0/ /g' abc.txt | perl -pe 'use MIME::QuotedPrint; $_=MIME::QuotedPrint::decode($_);' | grep "^Name:" | cut  -d' ' -f2-

我不知道为什么,但是原始文本包含“= C2 = A0”,它似乎与“”相同。所以我只是用“sed”来剥离它们。

致以最诚挚的问候,

尼尔。