How to extract multiple mailing addresses from PDF file using pdftotext
<p>I am using <code>pdftotext</code> in a bash script, trying to extract the names and addresses from PDF postage labels.</p>

<p>An example PDF file:</p>

<pre><code>Delivered By:

1st Class
Postage on Account GB

First Last
HouseName
Street
Town
County
Postcode

Customer Reference: 12400 / 203 1

32224983765

RETURN TO: MyName,
DoorNumber, Street, Town,
City, Postcode, Country

121-0434 905 20200-000 6190 C228

Delivered By:

1st Class
Postage on Account GB

First Last
HouseNumber
Street
Town
Postcode

Customer Reference: 12401 / 200 1

32224286536

RETURN TO: MyName,
DoorNumber, Street, Town,
City, Postcode, Country

121-0434 905 20200-000 6190 C414
</code></pre>

<p>Please note:</p>

<ul>
<li>The addresses do not have a fixed length ie. some consist of only 4 lines, and I have seen some with up to 6 lines.</li>
<li>The number of addresses in the PDF file will not be known in advance.</li>
</ul>

<p>So far, I have just got:</p>

<pre><code>pdftotext label.pdf - | grep -A10 "Postage on Account GB" | tail -n+3 | head -n -3
</code></pre>

<p>The <code>-</code> avoids creating a file. The <code>grep -A10</code> outputs the first 10 lines from the match <code>"Postage on Account GB"</code>. The <code>tail -n+3</code> removes the match and next line. The <code>head -n -3</code> removes the last 3 lines. That works fine when there's only one address in the file consisting of 6 lines, but I'm stuck when it comes to multiple addresses and with different lengths.</p>

<p>Put simply, I would like to extract the data from after the blank line after <code>Postage on Account GB</code>, until the line before the next blank line. Then format the output so that addresses are comma delimited and each on a new line, such as:</p>

<pre><code>First Last, HouseName, Street, Town, County, Postcode
First Last, HouseNumber, Street, Town, Postcode
</code></pre>