All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
remove_lines.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """
3 Simple script to remove lines from a file.
4 """
5 import os, sys, re
6 
7 def main():
8  if len(sys.argv) != 3:
9  print "Usage: %s <filename> <>\n" \
10  "\tRemoves from <filename> the lines matching <reg.exp.>" \
11  % os.path.basename(sys.argv[0])
12  sys.exit(1)
13 
14  filename, pattern = sys.argv[1:]
15  if not os.path.isfile(filename):
16  print "Error: cannot find file '%s'" % filename
17  sys.exit(1)
18 
19  try:
20  regexp = re.compile(pattern)
21  except re.error, v:
22  print "Error: invalid regular expression %r (%s)" % (pattern, v)
23  sys.exit(1)
24 
25  # read the file in memory skipping the matched lines
26  lines = [ l
27  for l in open(filename) ]
28  orig_size = len(lines)
29  lines = [ l
30  for l in lines
31  if not regexp.search(l) ]
32  final_size = len(lines)
33  # rename the original to make a backup copy
34  if os.path.exists(filename + "~"):
35  os.remove(filename + "~")
36  os.rename(filename, filename + "~")
37  # write out the file
38  open(filename, "w").writelines(lines)
39  print "Removed %d lines out of %d in file %s, matching pattern %r" \
40  % (orig_size - final_size, orig_size, filename, pattern)
41 
42 if __name__ == '__main__':
43  main()