|
1 | 1 | import argparse |
| 2 | +import glob |
2 | 3 |
|
3 | 4 | def main(): |
4 | | - parser = argparse.ArgumentParser(description="cat with -n option") |
5 | | - parser.add_argument("-n", action="store_true", help="number all output lines") |
6 | | - parser.add_argument("files", nargs="+", help="Files to read") |
| 5 | + parser = argparse.ArgumentParser(description="cat with -n and -b options") |
| 6 | + parser.add_argument("-n", action="store_true", help="Number all output lines") |
| 7 | + parser.add_argument("-b", action="store_true", help="Number non-blank lines (overrides -n)") |
| 8 | + parser.add_argument("files", nargs="+", help="Files to read (supports *.txt)") |
7 | 9 | args = parser.parse_args() |
8 | 10 |
|
| 11 | + # -b overrides -n |
| 12 | + number_all = args.n |
| 13 | + number_nonblank = args.b |
| 14 | + if number_all and number_nonblank: |
| 15 | + number_all = False |
| 16 | + |
| 17 | + # Expand wildcard patterns (e.g. *.txt) |
| 18 | + file_list = [] |
| 19 | + for pattern in args.files: |
| 20 | + matched_files = glob.glob(pattern) |
| 21 | + if matched_files: |
| 22 | + file_list.extend(matched_files) |
| 23 | + else: |
| 24 | + file_list.append(pattern) |
| 25 | + |
| 26 | + # Print contents of each file |
9 | 27 | line_number = 1 |
10 | | - for filename in args.files: |
| 28 | + for filename in file_list: |
11 | 29 | try: |
12 | 30 | with open(filename, "r") as f: |
13 | 31 | for line in f: |
14 | | - # Remove trailing newline for formatting |
15 | | - line_to_print = line.rstrip('\n') |
16 | | - if args.n: |
17 | | - print(f"{line_number:6}\t{line_to_print}") |
| 32 | + text = line.rstrip("\n") |
| 33 | + if number_nonblank: |
| 34 | + if text.strip(): # only number non-blank lines |
| 35 | + print(f"{line_number:6}\t{text}") |
| 36 | + line_number += 1 |
| 37 | + else: |
| 38 | + print() |
| 39 | + elif number_all: |
| 40 | + print(f"{line_number:6}\t{text}") |
18 | 41 | line_number += 1 |
19 | 42 | else: |
20 | | - print(line, end="") |
| 43 | + print(text) |
21 | 44 | except FileNotFoundError: |
22 | 45 | print(f"cat: {filename}: No such file or directory") |
23 | 46 |
|
|
0 commit comments