Skip to content

Commit 3afe937

Browse files
Implement basic functionality for cat command with line numbering options
1 parent b5089a2 commit 3afe937

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

‎implement-shell-tools/cat/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,8 @@ 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+
Run the Python implementation from this directory with `python cat.py sample-files/1.txt`
20+
or `python cat.py -n sample-files/1.txt sample-files/2.txt`. Use `-b` to number
21+
nonempty lines. Python 3 is required. Pass filenames explicitly if your shell
22+
does not expand wildcards.

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""Concatenate files, optionally numbering their lines."""
2+
3+
import argparse
4+
from pathlib import Path
5+
import sys
6+
7+
8+
def main():
9+
parser = argparse.ArgumentParser(description=__doc__)
10+
parser.add_argument("-n", action="store_true", help="number every line")
11+
parser.add_argument("-b", action="store_true", help="number nonempty lines")
12+
parser.add_argument("files", nargs="+")
13+
args = parser.parse_args()
14+
status = 0
15+
16+
for filename in args.files:
17+
line_number = 1
18+
try:
19+
with Path(filename).open(encoding="utf-8", newline="") as source:
20+
for line in source:
21+
number_line = args.n or (args.b and bool(line.strip()))
22+
if number_line:
23+
sys.stdout.write(f"{line_number:6}\t")
24+
line_number += 1
25+
sys.stdout.write(line)
26+
except (OSError, UnicodeError) as error:
27+
print(f"cat: {filename}: {error}", file=sys.stderr)
28+
status = 1
29+
30+
return status
31+
32+
33+
if __name__ == "__main__":
34+
sys.exit(main())

0 commit comments

Comments
 (0)