Skip to content

Commit 329ff4b

Browse files
implementing cat.py
1 parent 3f26722 commit 329ff4b

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

  • implement-shell-tools/cat

‎implement-shell-tools/cat/cat.py‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import argparse
2+
3+
parser = argparse.ArgumentParser(
4+
prog="check-for-cat",
5+
description="Implement my own version of cat",
6+
)
7+
8+
parser.add_argument("paths", nargs="+", help="The file paths to process")
9+
parser.add_argument("-n", action="store_true", help="Number lines")
10+
parser.add_argument("-b", action="store_true", help="Number non-blank lines")
11+
12+
args = parser.parse_args()
13+
14+
paths = args.paths
15+
show_n = args.n
16+
show_b = args.b
17+
18+
line_number = 1
19+
20+
for path in paths:
21+
with open(path, "r", encoding="utf-8") as f:
22+
content = f.read()
23+
24+
ends_with_newline = content.endswith("\n")
25+
lines = content.split("\n")
26+
if ends_with_newline:
27+
lines.pop()
28+
29+
new_lines = []
30+
for line in lines:
31+
if show_b:
32+
if line == "":
33+
new_lines.append(line)
34+
else:
35+
numbered = str(line_number).rjust(6, " ") + "\t" + line
36+
line_number += 1
37+
new_lines.append(numbered)
38+
elif show_n:
39+
numbered = str(line_number).rjust(6, " ") + "\t" + line
40+
line_number += 1
41+
new_lines.append(numbered)
42+
else:
43+
new_lines.append(line)
44+
lines = new_lines
45+
46+
output = "\n".join(lines)
47+
if ends_with_newline:
48+
output += "\n"
49+
print(output, end="")

0 commit comments

Comments
 (0)