Grishachev - grep

 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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
class Input:
def __init__(self):
self.arguments = {}
self.filename = ""
self.pattern = ""
def read(self):
idx = 1
while idx <= len(sys.argv[1:]) :
if sys.argv[idx][0]=='-':
if idx+1 <= len(sys.argv[1:]) and sys.argv[idx+1][0]!='-':
self.arguments[sys.argv[idx][1:]] = sys.argv[idx+1]
idx += 1
else:
self.arguments[sys.argv[idx][1:]] = True
else:
if self.filename != "":
self.pattern = sys.argv[idx]
else:
self.filename = sys.argv[idx]
if self.filename[0] != "/":
self.filename = "./" + self.filename
idx += 1
if not "e" in self.arguments:
self.arguments["e"] = self.pattern
if "i" in self.arguments:
self.arguments["e"] = self.arguments["e"].lower()
if "m" in self.arguments:
self.arguments["m"] = int(self.arguments["m"])
def processData(self,data):
line_idx = 1
count = 0
for line in data:
my_line = line
if "i" in self.arguments:
my_line = my_line.lower()
if re.search(self.arguments["e"],my_line):
if "n" in self.arguments:
print(str(line_idx)+": "+line)
else:
print(line)
count += 1
if "m" in self.arguments and count == self.arguments["m"]:
break
line_idx += 1
def process(self):
if self.filename != "":
with open(self.filename) as f:
content = f.read().splitlines()
self.processData(content)
else:
self.processData(sys.stdin.read().splitlines())
dat = Input()
dat.read()
dat.process()