Merge multiple lines with condition
<p>I have an xml file with the format</p>

<pre><code>&lt;movie&gt;
&lt;title&gt;Title&lt;/title&gt;
&lt;originaltitle&gt;Original Title&lt;/originaltitle&gt;
&lt;id&gt;ID1234&lt;/id&gt;
&lt;/movie&gt;
</code></pre>

<p>I am failing to use sed to merge the original title and the id tags, as below:</p>

<pre><code>&lt;movie&gt;
&lt;title&gt;Title&lt;/title&gt;
&lt;originaltitle&gt;ID1234 - Original Title&lt;/originaltitle&gt;
&lt;/movie&gt;
</code></pre>

<p>How can I save the match on the id, and reuse it elsewhere when modifying the title tag ? Note that the id tag is optional and therefore not always present, in which case, the original title should remain the same. I can write a script to loop over the file tags and achieve the same, but I thought someone might come up with an elegant sed solution for this. Any idea ? I can match each entry individually, but I don t know how to preserve one to use it later. So far I've got this, which does not work</p>

<pre><code>sed '/&lt;id&gt;(.*)&lt;\/id&gt;/ {s/&lt;sorttitle&gt;(.*)&lt;\/sorttitle&gt;/&lt;sorttitle&gt;\1 - \2&lt;\/sorttitle&gt;/}' movie.nfo
</code></pre>