forked from mjpost/bin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mid
executable file
·72 lines (61 loc) · 2.15 KB
/
mid
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
#!/usr/bin/env python3
"""
Prints the Nth line of a file or of each of a list of files.
Default input stream is sys.stdin.
Usage:
mid [-v] LINENO FILE1 [FILE2 FILE3 ...]
cat FILE | mid LINENO
where LINENO is the 1-indexed line number to display (or a range: M-N).
If `-v` is present, it will print a UNIX `head`-style header above each
file, identifying its provenance.
Author: Matt Post <[email protected]>
"""
import os
import sys
import gzip
import argparse
from itertools import zip_longest
def main(args):
if '-' in args.lines:
start, stop = map(lambda x: int(x), args.lines.split('-'))
elif '+' in args.lines:
start, stop = map(lambda x: int(x), args.lines.split('+'))
stop = start + stop
else:
start = int(args.lines)
stop = int(args.lines)
for i, lines in enumerate(zip_longest(*args.files), 1):
if i < start:
continue
if i > stop:
break
for j, line in enumerate(lines):
if line is not None:
if args.verbose:
print('=== {}'.format(args.files[j].name), line.rstrip(), '', sep='\n')
else:
print(line.rstrip(),)
def smart_read(filename: str):
try:
if filename == '-':
return sys.stdin
elif filename.endswith('.gz'):
return gzip.open(filename, mode='rt', encoding='utf-8')
else:
return open(filename, mode='rt', encoding='utf-8')
except FileNotFoundError as e:
print("Can't find file '{}'".format(filename))
sys.exit(1)
if __name__ == '__main__':
parser = argparse.ArgumentParser('Grabs a line from one or more files')
parser.add_argument('--verbose', '-v', default=False, action='store_true',
help='Display head-style file headers if there is more than one file')
parser.add_argument('lines',
help='The line number (N) or range (M-N or M:N) to display')
parser.add_argument('files',
nargs='*',
type=smart_read,
default=[sys.stdin],
help='The files to work with')
args = parser.parse_args()
main(args)