sed to extract a multiline subject from a mail message

I'm trying to extract a subject from a mail message but my subject example has 2 lines. How can I manage to extract it and write a string at the end of it?

Consider this example:

From: test@domain.com
Subject: Re: U =?ISO-8859-1?Q?qu=EA=3F!=3F!=3F!!_wtff_=E7=E3o_=ED=F3?=
 =?ISO-8859-1?Q?=FA=E1=E7?=
Date: 23/05/2012

Tried this:

sed 'N;s/^Subject:.*/Subject: \1 string/;P;D;'

And i get the ' invalid reference \1 on `s' command's RHS' error.

What output are you looking for?

What I want is to insert a string at the end of the subject. Like this:

From: test@domain.com 
Subject: Re: U =?ISO-8859-1?Q?qu=EA=3F!=3F!=3F!!_wtff_=E7=E3o_=ED=F3?=
 =?ISO-8859-1?Q?=FA=E1=E7?=  ***STRING*** 
Date: 23/05/2012

Tried this and it worked:

sed 'N;s/^Subject:\(.*\)/Subject:\1STRING/;P;D;' file.txt

But.... now I have another problem. When the subject has only 1 line, like this:

From: test@domain.com
Subject: Re: U =?ISO-8859-1?Q?qu=EA=3F!=3F!=3F!!_wtff_=E7=E3o_=ED=F3?= 
Date: 23/05/2012

The String gets written in the end of the 'Date:' line

How can I get both regex working (with 1 and 2 lines) on the same sed command?

There's no \(...\) expression for the \1 backreference to refer to.

Appending a string to the pattern space does not require backreferences:
Instead of s/\(.*\)/\1 string/ , use s/.*/& string/

If you want to append something to the line following the line that begins with "Subject:":

/^Subject:/{n; s/.*/& addendum/;}

Regards,
Alister

---------- Post updated at 02:37 PM ---------- Previous update was at 02:00 PM ----------

Test whether the pattern space contains \nDate: then insert the string appropriately (either before the newline if there's a match or at the end of the pattern space if there isn't).

Regards,
Alister

Hello Alister, thanks for your help!! but I was thinking in a more flexible way on doing that. I mean, what if the next line is not 'Date:'?

I want to do like this: "If the next line after '^Subject:' starts with a blank space, write the following string at the end of it.. if not, write at the end of the "^Subject:" line."

sed -e '/^Subject:/N; s/\n .*/& addendum/' -e t -e 's/\n/ addendum&/'

\n is only present after the N command.
The t command branches to the end of the script if the previous s command was successful, so the second s command is skipped.

that worked!! Thanks MadeInGermany!!!