This repository was archived by the owner on Mar 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrep_ab.py
More file actions
89 lines (72 loc) · 2.6 KB
/
grep_ab.py
File metadata and controls
89 lines (72 loc) · 2.6 KB
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
import re
import os
import argparse
def my_function(file_path, pattern, after=0, before=0):
""" Implementation of functionality of 'grep -A NUM -B NUM pattern file'.
:param file_path: path to file
:param pattern: str pattern
:param after: numbers of lines to be printed after matched line
:param before: numbers of lines to be printed before matched line
:return:
"""
res = []
step = 0
sep = '--\n'
with open(file_path, 'r') as open_file:
lines = open_file.readlines()
if not lines:
return ''
for i in range(len(lines)):
if re.search(pattern, lines[i]):
if not any([before, after]):
res.append(lines[i])
continue
bef = i-before if i-before > step else step
step = i + 1
aft = i + after + 1
if before and not after:
res.extend(lines[bef:i+1] + [sep])
elif before and after:
res.extend([sep] + lines[bef:i])
if after:
res.append(lines[i])
add_sep = True
for line in lines[i+1:aft]:
if re.search(pattern, line):
add_sep = False
break
res.append(line)
if add_sep:
res.append(sep)
if not res:
return ''
res = res[0: len(res)-1] if res[len(res)-1] == sep else res
res = res[1:] if res[0] == sep else res
if not res[len(res)-1].endswith('\n'):
res[len(res)-1] += '\n'
# check all
res2 = [e for e in res if e != sep]
if res2 == lines:
return ''.join(res2)
return ''.join(res)
def cli():
cli = argparse.ArgumentParser(
prog='Print matched line and lines before and after',
description='Implementation of command '
'"grep -A NUM -B NUM pattern file"')
cli.add_argument('-F', '--file', required=True, type=str,
help='path to file')
cli.add_argument('-P', '--pattern', required=True, type=str,
help='pattern')
cli.add_argument('-A', '--after', required=False, type=int,
help='Amount of lines after context')
cli.add_argument('-B', '--before', required=False, type=int,
help='Amount of lines before context')
return cli.parse_args()
def main():
args = cli()
input_file = os.path.abspath(args.file)
print my_function(input_file, str(args.pattern),
int(args.after), int(args.before))
if __name__ == "__main__":
main()