Skip to content

Commit 87d907b

Browse files
committed
feat: implement cat with -n and -b flags.
1 parent 69e566a commit 87d907b

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import sys
2+
3+
show_all_numbers = "-n" in sys.argv # this check will return true if found the flag
4+
show_non_blank_numbers = "-b" in sys.argv # this check will return true if found the flag
5+
6+
# 2. using filter get only the filenames everything except the script name and flags
7+
files = [arg for arg in sys.argv[1:] if arg not in ["-n", "-b"]]
8+
9+
if not files:
10+
print("Usage: python3 cat.py [-n] [-b] <filenames>")
11+
sys.exit()
12+
13+
line_count = 1
14+
# 3. Process each file
15+
for filename in files:
16+
try:
17+
with open(filename, "r") as file:
18+
for line in file:
19+
# Logic for -b
20+
if show_non_blank_numbers:
21+
if line.strip(): # If line is not empty
22+
print(f"{line_count:>6}\t{line}", end="")
23+
line_count += 1
24+
else:
25+
# Standard cat no flags
26+
print(line, end="")
27+
28+
# Logic for -n
29+
elif show_all_numbers:
30+
print(f"{line_count:>6}\t{line}", end="")
31+
line_count += 1
32+
33+
# Standard cat no flags
34+
else:
35+
print(line, end="")
36+
37+
# throw clear errors
38+
except FileNotFoundError:
39+
print(f"Error: {filename}: No such file or directory")
40+
except IsADirectoryError:
41+
print(f"Error: {filename}: Is a directory")

0 commit comments

Comments
 (0)