title: Python search and replace in a file
body: <p>I was trying to make a script to allow me to automate clean ups in the linux kernel a little bit. The first thing on my agenda was to remove braces({}) on if statements(c-styled) that wasnt  necessary for single statement blocks. Now the code I tried with my little knowledge of regex in python I got to a working state, such as:</p>
  
  <pre><code>if (!buf || !buf_len) {
          TRACE_RET(chip, STATUS_FAIL);
          }
  </code></pre>
  
  <p>and the script turn it into:</p>
  
  <pre><code>if (!buf || !buf_len) 
          TRACE_RET(chip, STATUS_FAIL);
  </code></pre>
  
  <p>Thats what I want but when I try it on real source files it seems like it randomly selects a if statement and take its deleted it beginning brace  and it has multiple statement blocks and it remove the ending brace far down the program usually on a else satement or a long if statement. </p>
  
  <p>So can someone please help me with make the script only touch an if statement if it has a single block statement and correctly delete it corresponding beginning and ending brace.</p>
  
  <p>The correct script looks like:</p>
  
  <pre><code>from sys import argv
  import os
  import sys
  import re
  
  get_filename = argv[1]
  target = open(get_filename)
  rename = get_filename + '.tmp'
  temp = open(rename, 'w')
  
  def if_statement():
      look=target.read()
      pattern=r'''if (\([^.)]*\)) (\{)(\n)([^&gt;]+)(\})'''
      replacement=r'''if \1 \3\4'''
      pattern_obj = re.compile(pattern, re.MULTILINE)
      outtext = re.sub(pattern_obj, replacement, look)
      temp.write(outtext)
      temp.close()
      target.close()
  
  
  if_statement()
  </code></pre>
  
  <p>Thanks in advance</p>