Skip to content

Commit 5223b1b

Browse files
committed
implement cat
1 parent e328bd5 commit 5223b1b

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(
4+
prog="cat",
5+
description="read, display, and concatenate text files.",
6+
)
7+
8+
parser.add_argument("-n", action="store_true", help="Number all output lines.")
9+
parser.add_argument("-b", action="store_true", help="Number non-blank output lines.")
10+
parser.add_argument("paths",nargs="+", help="The file to search")
11+
12+
args = parser.parse_args()
13+
14+
for path in args.paths:
15+
try:
16+
with open(path, mode='r', encoding='utf-8') as f:
17+
lines = f.readlines()
18+
19+
except Exception as err:
20+
print(f"Error reading file '{path}': {err}")
21+
continue
22+
23+
line_num = 1
24+
25+
for line in lines:
26+
if args.b:
27+
if line.strip() != "":
28+
print(f"{line_num:5} {line}", end="")
29+
line_num += 1
30+
else:
31+
print()
32+
elif args.n:
33+
print(f"{line_num:5} {line}", end="")
34+
line_num += 1
35+
else:
36+
print(line, end="")

0 commit comments

Comments
 (0)