title: How to remove blank lines between matches in Ansible
body: <p>I am trying to remove blank lines between two lines using Ansible but cannot get it work. My source file looks like this:</p>
  
  <pre><code>###This line has blank lines after it
  
  
  
  ###End of block
  
  #More lines
  </code></pre>
  
  <p>And I would like the result to look like this:</p>
  
  <pre><code>###This line has blank lines after it
  ###End of block
  
  #More lines
  </code></pre>
  
  <p>So far I have this task using the replace module:</p>
  
  <pre><code>- name: Remove blank lines between matches
    replace:
      path: /home/vagrant/abcd
      after: '###This line has blank lines after it'
      regexp: '(^\n)'
      replace: ''
      before: '###End of block'
  </code></pre>
  
  <p>But the task does not appear to work. In fact the task does not do anything to the source file.</p>
  
  <p>If I remove the last line of the task (<em>before: '###End of block'</em>). The lines do get removed but it also removes all blank lines until EOF which is not what I want. Here is the result with the last line removed:</p>
  
  <pre><code>###This line has blank lines after it###End of block
  #More lines
  </code></pre>
  
  <p>Which is not expected.</p>
  
  <p>I have a solution using sed but I want to keep it idempotent as possible. Maybe I need better regex?</p>
  
  <p>Any ideas please?</p>
  
  <p>Thanks.</p>