Skip to content

Commit 3602022

Browse files
Add total line for multiple files in wc
1 parent df5b8e5 commit 3602022

File tree

1 file changed

+24
-1
lines changed
  • implement-shell-tools/wc

1 file changed

+24
-1
lines changed

implement-shell-tools/wc/wc.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212

1313
args = parser.parse_args()
1414

15+
# Track totals
16+
total_lines = 0
17+
total_words = 0
18+
total_chars = 0
19+
1520
for path in args.paths:
1621
# Read the file
1722
with open(path, "r") as f:
@@ -22,11 +27,29 @@
2227
words = len(content.split())
2328
chars = len(content)
2429

30+
# Add to totals
31+
total_lines += lines
32+
total_words += words
33+
total_chars += chars
34+
2535
if args.lines:
2636
print(f"{lines:8} {path}")
2737
elif args.words:
2838
print(f"{words:8} {path}")
2939
elif args.chars:
3040
print(f"{chars:8} {path}")
3141
else:
32-
print(f"{lines:8}{words:8}{chars:8} {path}")
42+
print(f"{lines:8}{words:8}{chars:8} {path}")
43+
44+
45+
# Print totals if multiple files
46+
if len(args.paths) > 1:
47+
if args.lines:
48+
print(f"{total_lines:8} total")
49+
elif args.words:
50+
print(f"{total_words:8} total")
51+
elif args.chars:
52+
print(f"{total_chars:8} total")
53+
else:
54+
print(f"{total_lines:8}{total_words:8}{total_chars:8} total")
55+

0 commit comments

Comments
 (0)