Appending data with additional information to text in a file
<p>I have a text file containing thousands of lines of code and I would like to replace certain elements as follows:</p>

<p>Text from file1:</p>

<pre><code>serverfarm host foobar2:443
  failaction reassign
  probe tcp111-probe
  rserver foobar1 443
  rserver foobar2 443
</code></pre>

<p>Text with additional information that I would like to append to original file text (file2):</p>

<pre><code>rserver host foobar1
  ip address 1.1.1.1
  inservice
rserver host foobar2
  ip address 1.1.1.2
  inservice
</code></pre>

<p>So we can see that in the original file the <code>rserver</code> line does not capture the IP address but I have this information in the other file.  </p>

<p>Before:</p>

<pre><code>rserver foobar1 443
</code></pre>

<p>After (desired output)</p>

<p><code>rserver foobar1 443</code> &lt;--- Keep original text</p>

<p><code>rserver host foobar1</code>  &lt;--- This and following two lines should be added below original text</p>

<pre><code>ip address 1.1.1.1

inservice
</code></pre>

<p>There is a direct mapping between the original text string <code>"rserver foobar1 443"</code> (remove 3rd text block) and the first line of the replacement text <code>"rserver host foobar1"</code> (remove 2nd text block = host).</p>

<p>Is it possible to do this with a python dictionary or similar approach?  I would appreciate it if someone could show me how to do this in Python and I will then use this approach when doing similar tasks.</p>

<p>The idea is to write a custom parser/translator like the following:</p>

<pre><code>replacements = {}
with open('file2.txt') as f:
    for l in f:
        l = l.strip()
        if l.startswith('rserver'):
            server_header = l
            server = l.split()
            server_name = server[2]
        elif 'ip address' in l:
            ip_address = l
        elif 'service' in l:
            service = l
            replacements[server_name] = (server_header, ip_address, service)

with open('file1.txt') as f, open('out.txt', 'w') as out:
    for l in f:
        l = l.rstrip()
        if 'rserver' in l:
            server = l.split()
            server_name = server[1]
            out.write(l + '\n')
            out.write('  ' + replacements[server_name][0] + '\n')
            out.write('    ' + replacements[server_name][1] + '\n')
            out.write('    ' + replacements[server_name][2] + '\n')                
        else:
            out.write(l + '\n')
</code></pre>

<p><strong>Output</strong> <em>(out.txt)</em></p>

<pre><code>serverfarm host foobar2:443
  failaction reassign
  probe tcp111-probe
  rserver foobar1 443
  rserver host foobar1
    ip address 1.1.1.1
    inservice
  rserver foobar2 443
  rserver host foobar2
    ip address 1.1.1.2
    inservice
</code></pre>

python