-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathmy-wc.py
More file actions
104 lines (76 loc) · 2.05 KB
/
Copy pathmy-wc.py
File metadata and controls
104 lines (76 loc) · 2.05 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
import sys
import glob
def count_file(path):
with open(path, "rb") as f:
content = f.read()
byte_count = len(content)
text = content.decode("utf-8", errors="ignore")
line_count = text.count("\n")
word_count = len(text.split())
return line_count, word_count, byte_count
def expand(paths):
files = []
for p in paths:
matches = glob.glob(p)
if matches:
files.extend(matches)
else:
files.append(p)
return files
def main():
args = sys.argv[1:]
show_l = False
show_w = False
show_c = False
paths = []
# parse args
for a in args:
if a == "-l":
show_l = True
elif a == "-w":
show_w = True
elif a == "-c":
show_c = True
else:
paths.append(a)
# default: show all
if not (show_l or show_w or show_c):
show_l = show_w = show_c = True
files = expand(paths)
total_l = 0
total_w = 0
total_c = 0
results = []
for file in files:
try:
l, w, c = count_file(file)
except FileNotFoundError:
print(f"wc: {file}: No such file or directory", file=sys.stderr)
continue
total_l += l
total_w += w
total_c += c
results.append((l,w,c, file))
# print per-file results (GNU-aligned formatting)
for l, w, c, file in results:
parts = []
if show_l:
parts.append(f"{l:3}")
if show_w:
parts.append(f"{w:4}")
if show_c:
parts.append(f"{c:4}")
print("".join(parts) + " " + file)
# print total if multiple files
if len(results) > 1:
parts = []
if show_l:
parts.append(f"{total_l:3}")
if show_w:
parts.append(f"{total_w:4}")
if show_c:
parts.append(f"{total_c:4}")
print("".join(parts) + " total")
if __name__ == "__main__":
main()