Skip to content

Commit a9bbd58

Browse files
committed
feat: implement wc with -l -w -c flags and totals.
1 parent 46111db commit a9bbd58

File tree

1 file changed

+54
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+54
-0
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import sys
2+
import os
3+
4+
# Flag Detection
5+
show_lines = "-l" in sys.argv
6+
show_words = "-w" in sys.argv
7+
show_chars = "-c" in sys.argv
8+
9+
# If no flags then show all.
10+
show_all = not (show_lines or show_words or show_chars)
11+
12+
# Filter files excluding flags
13+
files = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
14+
15+
# Total counters
16+
total_l, total_w, total_c = 0, 0, 0
17+
18+
for filename in files:
19+
try:
20+
with open(filename, 'r') as f:
21+
lines = f.readlines()
22+
23+
# files calculation
24+
l_count = len(lines)
25+
w_count = sum(len(line.split()) for line in lines)
26+
# os.path.getsize for bytes, in .js I used const bytes = Buffer.byteLength(content);
27+
c_count = os.path.getsize(filename)
28+
29+
# Update totals
30+
total_l += l_count
31+
total_w += w_count
32+
total_c += c_count
33+
34+
# Printing Logic
35+
output = []
36+
if show_lines or show_all: output.append(f"{l_count:>8}")
37+
if show_words or show_all: output.append(f"{w_count:>8}")
38+
if show_chars or show_all: output.append(f"{c_count:>8}")
39+
40+
print(f"{''.join(output)} {filename}")
41+
42+
except FileNotFoundError:
43+
print(f"wc: {filename}: No such file or directory")
44+
except IsADirectoryError:
45+
print(f"wc: {filename}: Is a directory")
46+
print(f"{'0':>8} {'0':>8} {'0':>8} {filename}")
47+
48+
# Print Total if there were multiple files
49+
if len(files) > 1:
50+
output_total = []
51+
if show_lines or show_all: output_total.append(f"{total_l:>8}")
52+
if show_words or show_all: output_total.append(f"{total_w:>8}")
53+
if show_chars or show_all: output_total.append(f"{total_c:>8}")
54+
print(f"{''.join(output_total)} total")

0 commit comments

Comments
 (0)