Skip to content

Commit 1bce56a

Browse files
committed
Add python implementation of catCommand and .gitignore file
1 parent 407b010 commit 1bce56a

2 files changed

Lines changed: 68 additions & 1 deletion

File tree

implement-shell-tools/cat/README.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Implement `cat`
1+
# Implement `cat` in python
22

33
You should already be familiar with the `cat` command line tool.
44

@@ -15,3 +15,20 @@ It must act the same as `cat` would, if run from the directory containing this R
1515
Matching any additional behaviours or flags are optional stretch goals.
1616

1717
We recommend you start off supporting no flags, then add support for `-n`, then add support for `-b`.
18+
19+
*========commands for running the scripts========
20+
21+
* No flags
22+
python cat.py sample-files/1.txt
23+
24+
* Number every line (-n)
25+
python cat.py -n sample-files/1.txt
26+
27+
* Display all files in directory(shell expands *.txt)
28+
python cat.py sample-files/*.txt
29+
30+
* Number every line across multiple files(including empty ones)
31+
python cat.py -n sample-files/*.txt
32+
33+
* Number non-empty lines only (-b)
34+
python cat.py -b sample-files/3.txt

implement-shell-tools/cat/cat.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import argparse
2+
# -------------------------------------------
3+
# Set up the argument parser
4+
# -------------------------------------------
5+
6+
parser = argparse.ArgumentParser(
7+
prog ="display-file-content",
8+
description = "Implement cat command with -n and -b flag support",
9+
)
10+
11+
parser.add_argument("-n", "--number-all-lines",
12+
action="store_true",
13+
help="Number every line in the file"
14+
)
15+
16+
parser.add_argument("-b", "--number-non-empty-lines",
17+
action="store_true",
18+
help="Number non empty lines in the file"
19+
)
20+
21+
parser.add_argument("paths", nargs="+", help="File paths to process")
22+
23+
args = parser.parse_args()
24+
25+
# -------------------------------------------
26+
# Implement functionality
27+
# -------------------------------------------
28+
29+
line_number = 1
30+
31+
for filepath in args.paths:
32+
with open(filepath, "r", encoding="utf-8") as f:
33+
content = f.read()
34+
35+
lines = content.split("\n")
36+
37+
for line in lines:
38+
if args.number_all_lines:
39+
print(f"{line_number} {line}")
40+
line_number += 1
41+
42+
elif args.number_non_empty_lines:
43+
if line.strip() == "":
44+
print(line)
45+
else:
46+
print(f"{line_number} {line}")
47+
line_number +=1
48+
49+
else:
50+
print(line)

0 commit comments

Comments
 (0)