This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmygrep.py
142 lines (124 loc) · 5.33 KB
/
mygrep.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import sys, os
from argparse import ArgumentParser, FileType
#------------------------------------------------------------------------------
GREEN = '\033[32m'
PRETTY_GREEN = '\033[92m'
END_COLOR = '\033[0m'
def index_find(pattern, string, ignore_case):
"""Find index of pattern match in string. Returns -1 if not found."""
if ignore_case:
pattern = pattern.lower()
string = string.lower()
for i in range(len(string)):
for j in range(len(pattern)):
if string[i+j] != pattern[j]:
break
elif j == len(pattern) - 1:
return i
#vlah
blah = 1
return -1
def color_find(pattern, string, ignore_case):
"""Find all matches of pattern in string. Returns colored string, or empty string if not found."""
result = ''
index = index_find(pattern, string, ignore_case)
while index != -1:
result += string[:index]
result += PRETTY_GREEN + string[index:index + len(pattern)] + END_COLOR
string = string[index + len(pattern):]
index = index_find(pattern, string, ignore_case)
return result if result == '' else result + string
def get_match(pattern, string, color, ignore_case):
"""Find the pattern in the string. Returns the match result or the empty string if not found."""
if color:
return color_find(pattern, string, ignore_case)
else:
index = index_find(pattern, string, ignore_case)
return string if index != -1 else ''
def print_result(print_header, header, print_lineno, lineno, print_line, line):
"""Print result to standard output."""
result = ''
if print_header:
result += '%s' % header
if print_lineno:
if len(result) > 0:
result += ':'
result += '%d' % lineno
if print_line:
if len(result) > 0:
result += ':'
result += line
sys.stdout.write('%s\n' % result.strip('\n'))
def grep_file(filename, pattern, color, ignore_case, print_headers,
print_lineno, print_lines):
"""Search a single file or standard input."""
text = sys.stdin if filename == '(standard input)' else open(filename, 'r')
line = text.readline()
lineno = 1
while line:
result = get_match(pattern, line, color, ignore_case)
if len(result) > 0:
print_result(print_headers, filename, print_lineno, lineno,
print_lines, result)
if print_headers and not print_lines: # files-with-matches option
break
line = text.readline()
lineno += 1
text.close()
def grep_files(paths, pattern, recurse, color, ignore_case, print_headers,
print_lineno, print_line):
"""Search files and directories."""
for path in paths:
if os.path.isfile(path) or path == '(standard input)':
grep_file(path, pattern, color, ignore_case, print_headers,
print_lineno, print_line)
else:
if recurse:
more_paths = [path + '/' + child for child in os.listdir(path)]
grep_files(more_paths, pattern, recurse, color, ignore_case,
print_headers, print_lineno, print_line)
else:
sys.stdout.write('grep: %s: Is a directory\n' % path)
def setup_parser():
"""Configure command line argument parser object."""
parser = ArgumentParser(description='Find matches of a pattern in ' \
'lines of file(s).', add_help=False)
parser.add_argument('--help', action='help', help='show this help ' \
'message and exit')
parser.add_argument('pattern', type=str, help='the pattern to find')
parser.add_argument('files', metavar='FILES', nargs='*', default=['-'],
help='the files(s) to search')
parser.add_argument('--color', '--colour', action='store_true',
help='highlight matches')
parser.add_argument('-h', '--no-filename', action='store_true',
help='print without filename headers')
parser.add_argument('-i', '--ignore-case', action='store_true',
help='case-insensitive search')
parser.add_argument('-l', '--files-with-matches', action='store_true',
help='print only filenames with matches')
parser.add_argument('-n', '--line-number', action='store_true',
help='print line numbers, indexed from 1')
parser.add_argument('-R', '-r', '--recursive', action='store_true',
help='recursively search directories')
return parser
DEFAULT_PRINT_OPTIONS = (False, False, True)
def main():
parser = setup_parser()
args = parser.parse_args()
pattern = args.pattern
files = [f if f!= '-' else '(standard input)' for f in args.files]
print_headers, print_lineno, print_lines = DEFAULT_PRINT_OPTIONS
if args.files_with_matches:
print_headers = True
print_lines = False
else:
if args.recursive or len(files) > 1:
print_headers = True
if args.line_number:
print_lineno = True
if args.no_filename:
print_headers = False
grep_files(files, pattern, args.recursive, args.color, args.ignore_case,
print_headers, print_lineno, print_lines)
if __name__ == '__main__':
main()