summaryrefslogtreecommitdiffstats
path: root/Lib/grep.py
blob: 767498bd3229f2d424bb584c965a3ca091e75dd0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 'grep'

import regexp
import string

def grep(expr, filename):
	match = regexp.compile(expr).match
	fp = open(filename, 'r')
	lineno = 0
	while 1:
		line = fp.readline()
		if not line: break
		lineno = lineno + 1
		res = match(line)
		if res:
			#print res
			start, end = res[0]
			if line[-1:] = '\n': line = line[:-1]
			prefix = string.rjust(`lineno`, 3) + ': '
			print prefix + line
			if 0:
				line = line[:start]
				if '\t' not in line:
					prefix = ' ' * (len(prefix) + start)
				else:
					prefix = ' ' * len(prefix)
					for c in line:
						if c <> '\t': c = ' '
						prefix = prefix + c
				if start = end: prefix = prefix + '\\'
				else: prefix = prefix + '^'*(end-start)
				print prefix