lines fails if a non existent line asked
[hband-tools.git] / user-tools / mail-extract-raw-headers
blob028396092c6523476952a2d4ddfc5c2a95679543
1 #!/usr/bin/env perl
3 =pod
5 =head1 NAME
7 mail-extract-raw-headers - Get named headers from RFC822-format input.
9 =head1 SYNOPSIS
11 mail-extract-raw-headers [OPTIONS] <NAME> [<NAME> [...]]
13 =head1 OPTIONS
15 =over 4
17 =item -k, --keep-newlines, --keep-linefeeds
19 Keep linefeeds in multiline text.
21 =item -n, --header-names
23 Output the header name(s) too, not only the contents.
25 =back
27 =cut
30 use Getopt::Long qw/:config no_ignore_case bundling no_getopt_compat/;
31 use Pod::Usage;
32 #use Data::Dumper;
33 no if ($] >= 5.018), 'warnings' => 'experimental::smartmatch';
35 $OptKeepLF = 0;
36 $OptNames = 0;
38 GetOptions(
39 'k|keep-newlines|keep-linefeeds' => \$OptKeepLF,
40 'n|header-names' => \$OptNames,
41 'help|?' => sub { pod2usage(-exitval=>0, -verbose=>99); },
42 ) or pod2usage(-exitval=>2, -verbose=>99);
44 if(not @ARGV)
46 pod2usage(-exitval=>2, -verbose=>99);
49 @asked_headers = map {lc} @ARGV;
52 sub getheaders($)
54 my $hname = lc shift;
55 my @return;
57 for my $hdr_ref (@Headers)
59 if(lc $hdr_ref->{"name"} eq $hname)
61 push @return, $hdr_ref->{"content"};
64 return @return;
67 @found_headers = ();
69 # read headers
70 while(<STDIN>)
72 if(/^\r?\n?$/)
74 # End of Headers
75 last;
78 # does not care line ending
79 s/\r?\n?$//;
81 if(my($hdr_name, $content) = /^(\S+?):[ ]?(.*)/)
83 if(lc $hdr_name ~~ @asked_headers)
85 my $hdr_name_pretty = $hdr_name;
86 $hdr_name_pretty =~ s/[^-]*/\L\u$&/g;
88 my $hdr_hash = { "name" => $hdr_name, "pretty_name" => $hdr_name_pretty, "content" => $content, };
89 push @found_headers, $hdr_hash;
90 $last_hdr_ref = $hdr_hash;
92 else
94 $last_hdr_ref = undef;
97 elsif(/^\s+(.*)/ and defined $last_hdr_ref)
99 # it is a folded header
100 $last_hdr_ref->{"content"} .= "\n" if $OptKeepLF;
101 $last_hdr_ref->{"content"} .= $1;
105 print join "", map {
106 if($OptNames)
108 sprintf "%s: %s\n", $_->{'pretty_name'}, $_->{'content'};
110 else
112 sprintf "%s\n", $_->{'content'};
114 } @found_headers;