grep.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # usage:
  2. # grep.py -d <directory> -f <text>
  3. #
  4. # <directory> is a folder, with subfolders, containing .svg files. In each svg file in the directory or its children
  5. # look for <text>
  6. import getopt, sys, os, re
  7. def usage():
  8. print """
  9. usage:
  10. grep.py -d [directory] -f [text] -n
  11. directory is a folder containing .svg files.
  12. In each svg file in the directory or its subfolders,
  13. look for [text]
  14. """
  15. def main():
  16. try:
  17. opts, args = getopt.getopt(sys.argv[1:], "hnd:f:", ["help", "not", "directory", "find"])
  18. except getopt.GetoptError, err:
  19. # print help information and exit:
  20. print str(err) # will print something like "option -a not recognized"
  21. usage()
  22. sys.exit(2)
  23. outputDir = None
  24. findtext = ""
  25. gotnot = 0
  26. for o, a in opts:
  27. #print o
  28. #print a
  29. if o in ("-d", "--directory"):
  30. outputDir = a
  31. elif o in ("-h", "--help"):
  32. usage()
  33. sys.exit(2)
  34. elif o in ("-f", "--find"):
  35. findtext = a;
  36. elif o in ("-n", "--not"):
  37. gotnot = 1;
  38. else:
  39. assert False, "unhandled option"
  40. if(not(outputDir)):
  41. usage()
  42. sys.exit(2)
  43. print "finding text " + findtext
  44. for root, dirs, files in os.walk(outputDir, topdown=False):
  45. for filename in files:
  46. if (filename.endswith(".svg")):
  47. infile = open(os.path.join(root, filename), "r")
  48. svg = infile.read();
  49. infile.close();
  50. rslt = svg.find(findtext)
  51. if gotnot and (rslt < 0):
  52. print "{0}:{1}".format(os.path.join(root, filename), rslt)
  53. if (not gotnot) and (rslt > -1):
  54. print "{0}:{1}".format(os.path.join(root, filename), rslt)
  55. if __name__ == "__main__":
  56. main()