| # Gaudi Framework, version v22r2 |

Home |  | Generated: Tue May 10 2011

# remove_lines.py

Go to the documentation of this file.

    00001 #!/usr/bin/env python
    00002 """
    00003 Simple script to remove lines from a file.
    00004 """
    00005 import os, sys, re
    00006
    00007 def main():
    00008     if len(sys.argv) != 3:
    00009         print "Usage: %s <filename> <>\n" \
    00010               "\tRemoves from <filename> the lines matching <reg.exp.>" \
    00011               % os.path.basename(sys.argv[0])
    00012         sys.exit(1)
    00013
    00014     filename, pattern = sys.argv[1:]
    00015     if not os.path.isfile(filename):
    00016         print "Error: cannot find file '%s'" % filename
    00017         sys.exit(1)
    00018
    00019     try:
    00020         regexp = re.compile(pattern)
    00021     except re.error, v:
    00022         print "Error: invalid regular expression %r (%s)" % (pattern, v)
    00023         sys.exit(1)
    00024
    00025     # read the file in memory skipping the matched lines
    00026     lines = [ l
    00027               for l in open(filename) ]
    00028     orig_size = len(lines)
    00029     lines = [ l
    00030               for l in lines
    00031               if not regexp.search(l) ]
    00032     final_size = len(lines)
    00033     # rename the original to make a backup copy
    00034     if os.path.exists(filename + "~"):
    00035         os.remove(filename + "~")
    00036     os.rename(filename, filename + "~")
    00037     # write out the file
    00038     open(filename, "w").writelines(lines)
    00039     print "Removed %d lines out of %d in file %s, matching pattern %r" \
    00040           % (orig_size - final_size, orig_size, filename, pattern)
    00041
    00042 if __name__ == '__main__':
    00043     main()

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Defines