Skip to content

Commit 85c60fc

Browse files
Implement basic, -n and -b functionality for 'cat' command alternative
1 parent 407b010 commit 85c60fc

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import argparse
2+
3+
4+
parser = argparse.ArgumentParser(
5+
prog="cat",
6+
description="An alternative to the 'cat' command",
7+
)
8+
9+
parser.add_argument("files", nargs="+", help="The file(s) to process")
10+
parser.add_argument("-n", "--number", action="store_true", help="Number all output lines")
11+
parser.add_argument("-b", "--number-nonblank", action="store_true", help="Number non-blank output lines")
12+
13+
args = parser.parse_args()
14+
15+
16+
17+
def print_line(line, padding_width, line_number=None):
18+
"""Helper function to print a line with optional line numbering."""
19+
if line_number is not None:
20+
print(f"{str(line_number).rjust(padding_width)} {line}")
21+
else:
22+
print(line)
23+
24+
line_number = 1
25+
padding_width = 6
26+
27+
for file in args.files:
28+
with open(file, "r") as f:
29+
# read the content and split the lines ready to process as needed
30+
content = f.read().splitlines()
31+
32+
for line in content:
33+
# use .strip() to remove leading and trailing whitespace or /n
34+
if args.number_nonblank and line.strip():
35+
# number non-blank lines only
36+
print_line(line, padding_width, line_number)
37+
line_number += 1
38+
elif args.number:
39+
# number all lines
40+
print_line(line, padding_width, line_number)
41+
line_number += 1
42+
else:
43+
# no flags
44+
print_line(line, padding_width)

0 commit comments

Comments
 (0)