Skip to content

Commit 84c8f72

Browse files
committed
feat: implement cat cmd with the -n and -b flags
1 parent 4350f48 commit 84c8f72

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
11
node_modules
2+
demo*
3+
.*

implement-shell-tools/cat/cat.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import sys
5+
6+
parser = argparse.ArgumentParser(
7+
prog='cat',
8+
description='CLI tool to concatenate and print files',
9+
)
10+
11+
parser.add_argument('-n', '--number', action='store_true', help='Number all outputs, starting at 1')
12+
parser.add_argument('-b', '--nonBlank', action='store_true', help='Number only non-blank lines, starting at 1')
13+
parser.add_argument('files', nargs='*', help='Files to read')
14+
15+
args = parser.parse_args()
16+
# print(args.number, args.nonBlank, args.files)
17+
# print(sys.argv[0], sys.argv[1])
18+
19+
20+
for file in args.files:
21+
count = 1
22+
try:
23+
with open(file, 'r') as f:
24+
for line in f:
25+
if args.nonBlank:
26+
if line.strip():
27+
print(f"{str(count).rjust(6)}\t{line}", end='')
28+
count += 1
29+
else:
30+
print(line, end="")
31+
elif args.number:
32+
print(f"{str(count).rjust(6)}\t{line}", end='')
33+
count +=1
34+
else:
35+
print(f"{line}", end="")
36+
37+
except FileNotFoundError:
38+
print(f"cat: {file}: No such file or directory.", file=sys.stderr)

0 commit comments

Comments
 (0)