grep.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # 'grep'
  2. import regex
  3. from regex_syntax import *
  4. opt_show_where = 0
  5. opt_show_filename = 0
  6. opt_show_lineno = 1
  7. def grep(pat, *files):
  8. return ggrep(RE_SYNTAX_GREP, pat, files)
  9. def egrep(pat, *files):
  10. return ggrep(RE_SYNTAX_EGREP, pat, files)
  11. def emgrep(pat, *files):
  12. return ggrep(RE_SYNTAX_EMACS, pat, files)
  13. def ggrep(syntax, pat, files):
  14. if len(files) == 1 and type(files[0]) == type([]):
  15. files = files[0]
  16. global opt_show_filename
  17. opt_show_filename = (len(files) != 1)
  18. syntax = regex.set_syntax(syntax)
  19. try:
  20. prog = regex.compile(pat)
  21. finally:
  22. syntax = regex.set_syntax(syntax)
  23. for filename in files:
  24. fp = open(filename, 'r')
  25. lineno = 0
  26. while 1:
  27. line = fp.readline()
  28. if not line: break
  29. lineno = lineno + 1
  30. if prog.search(line) >= 0:
  31. showline(filename, lineno, line, prog)
  32. fp.close()
  33. def pgrep(pat, *files):
  34. if len(files) == 1 and type(files[0]) == type([]):
  35. files = files[0]
  36. global opt_show_filename
  37. opt_show_filename = (len(files) != 1)
  38. import re
  39. prog = re.compile(pat)
  40. for filename in files:
  41. fp = open(filename, 'r')
  42. lineno = 0
  43. while 1:
  44. line = fp.readline()
  45. if not line: break
  46. lineno = lineno + 1
  47. if prog.search(line):
  48. showline(filename, lineno, line, prog)
  49. fp.close()
  50. def showline(filename, lineno, line, prog):
  51. if line[-1:] == '\n': line = line[:-1]
  52. if opt_show_lineno:
  53. prefix = `lineno`.rjust(3) + ': '
  54. else:
  55. prefix = ''
  56. if opt_show_filename:
  57. prefix = filename + ': ' + prefix
  58. print prefix + line
  59. if opt_show_where:
  60. start, end = prog.regs()[0]
  61. line = line[:start]
  62. if '\t' not in line:
  63. prefix = ' ' * (len(prefix) + start)
  64. else:
  65. prefix = ' ' * len(prefix)
  66. for c in line:
  67. if c != '\t': c = ' '
  68. prefix = prefix + c
  69. if start == end: prefix = prefix + '\\'
  70. else: prefix = prefix + '^'*(end-start)
  71. print prefix