|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import sys |
| 3 | +import glob |
| 4 | +import os |
| 5 | + |
| 6 | +def count_file(filename, count_lines, count_words, count_bytes): |
| 7 | + try: |
| 8 | + with open(filename, "rb") as f: # open in binary to count bytes correctly |
| 9 | + data = f.read() |
| 10 | + except FileNotFoundError: |
| 11 | + print(f"wc: {filename}: No such file or directory", file=sys.stderr) |
| 12 | + return None |
| 13 | + |
| 14 | + text = data.decode(errors="ignore") |
| 15 | + lines = text.splitlines() |
| 16 | + |
| 17 | + l = len(lines) |
| 18 | + w = len(text.split()) |
| 19 | + c = len(data) |
| 20 | + |
| 21 | + results = [] |
| 22 | + if count_lines: |
| 23 | + results.append(str(l)) |
| 24 | + if count_words: |
| 25 | + results.append(str(w)) |
| 26 | + if count_bytes: |
| 27 | + results.append(str(c)) |
| 28 | + |
| 29 | + if not (count_lines or count_words or count_bytes): |
| 30 | + # default: all three |
| 31 | + results = [str(l), str(w), str(c)] |
| 32 | + |
| 33 | + return results, filename, (l, w, c) |
| 34 | + |
| 35 | +def main(): |
| 36 | + args = sys.argv[1:] |
| 37 | + |
| 38 | + count_lines = "-l" in args |
| 39 | + count_words = "-w" in args |
| 40 | + count_bytes = "-c" in args |
| 41 | + |
| 42 | + # remove flags from args |
| 43 | + files = [arg for arg in args if arg not in ("-l", "-w", "-c")] |
| 44 | + |
| 45 | + if not files: |
| 46 | + print("wc: missing file operand", file=sys.stderr) |
| 47 | + sys.exit(1) |
| 48 | + |
| 49 | + expanded_files = [] |
| 50 | + for f in files: |
| 51 | + expanded_files.extend(glob.glob(f)) |
| 52 | + |
| 53 | + if not expanded_files: |
| 54 | + print("wc: no matching files", file=sys.stderr) |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + total_l, total_w, total_c = 0, 0, 0 |
| 58 | + |
| 59 | + for filename in expanded_files: |
| 60 | + result = count_file(filename, count_lines, count_words, count_bytes) |
| 61 | + if result: |
| 62 | + res, name, (l, w, c) = result |
| 63 | + print(f"{' '.join(res)} {name}") |
| 64 | + total_l += l |
| 65 | + total_w += w |
| 66 | + total_c += c |
| 67 | + |
| 68 | + if len(expanded_files) > 1: |
| 69 | + total_results = [] |
| 70 | + if count_lines: |
| 71 | + total_results.append(str(total_l)) |
| 72 | + if count_words: |
| 73 | + total_results.append(str(total_w)) |
| 74 | + if count_bytes: |
| 75 | + total_results.append(str(total_c)) |
| 76 | + if not (count_lines or count_words or count_bytes): |
| 77 | + total_results = [str(total_l), str(total_w), str(total_c)] |
| 78 | + print(f"{' '.join(total_results)} total") |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + main() |
0 commit comments