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>If you are running a Linux distro, then you can use awk command and pipe it with grep.</p>

<p>If you want a solution with python, then the complexity is going to be O(n.m), where n is the number of lines in first file and m is the number of lines in second file.</p>

<p>Algorithm in python:</p>

<pre><code>open a new file, file3
file1 = f.open(path to file 1)
n = number of lines in file1
file2 = f.open(path to file 2)
m = number of lines in file 2
for i in range(n):
   r = readline(file1)
   copy line into file3
   convert r to array and check to see if r[0] is "rserver"
   if r[0]=="rserver" then:
      for j in range(m):
         k = readline(file2)
         convert k to array and check to see if k[0] is "rserver"
         if k[0]=="rserver" then:
            merge required number of lines from file2 into file3
            increment j by x
close all files
</code></pre>

<p>Hope this helps!</p>

python