Skip to content

Commit 0c5aeb2

Browse files
committed
cat function to cat the formatted lines
1 parent 108fef7 commit 0c5aeb2

1 file changed

Lines changed: 24 additions & 3 deletions

File tree

  • implement-shell-tools/cat

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

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,11 @@ def read_file(path):
2828

2929
# -b (number the non-empty lines) takes priority over -n (number all lines)
3030
# if both are present
31-
def format_lines(lines, number_all=False, number_non_empty=False):
31+
def format_lines(lines, number_all=False, number_nonempty=False):
3232
"""Returns a list of formatted output lines"""
3333
output = []
3434

35-
if number_non_empty:
35+
if number_nonempty:
3636
line_num = 0
3737
for line in lines:
3838
if line == "":
@@ -48,16 +48,37 @@ def format_lines(lines, number_all=False, number_non_empty=False):
4848
else:
4949
output = lines
5050

51+
return output
52+
5153

5254
# TODO: runner function to call read_file, and feed it into formatLines, then print
55+
def cat_file(path, number_all=False, number_nonempty=False):
56+
"""
57+
Calls read_file -> format_lines -> prints formatted line.
58+
Returns True if file read successfully, else returns False
59+
60+
If failed to read file, prints error to stderr
61+
"""
62+
content, error = read_file(path)
63+
if (error):
64+
print(error, file=sys.stderr)
65+
return False
66+
67+
# splitlines automatically trims trailing empty lines
68+
lines = content.splitlines()
69+
for line in format_lines(lines, number_all, number_nonempty):
70+
print(line)
71+
72+
return True
73+
5374

5475
def main():
5576
# cat exits with error code 1 if any file read fails
5677
file_error = False
5778

5879
for path in args.paths:
5980
line_num = 1
60-
is_success = cat_file(path)
81+
is_success = cat_file(path, args.n, args.b)
6182

6283
if not is_success:
6384
file_error = True

0 commit comments

Comments
 (0)