Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions implement-shell-tools/cat/cat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import argparse
import sys

parser = argparse.ArgumentParser(prog="cat")
parser.add_argument("-n", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("files", nargs="+")

args = parser.parse_args()

for file in args.files:
line_number = 1

with open(file) as f:
for line in f:
should_number = args.n or (args.b and line.strip())

if should_number:
print(f"{line_number:6}\t{line}", end="")
line_number += 1
else:
print(line, end="")
43 changes: 43 additions & 0 deletions implement-shell-tools/ls/ls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import argparse
import os

parser = argparse.ArgumentParser(prog="ls")
parser.add_argument("-1", dest="one", action="store_true")
parser.add_argument("-a", action="store_true")
parser.add_argument("paths", nargs="*", default=["."])

args = parser.parse_args()


def get_files(path):
files = sorted(os.listdir(path))

if args.a:
return [".", ".."] + files

return [f for f in files if not f.startswith(".")]


# Print all files first
for path in args.paths:
if not os.path.isdir(path):
if args.one:
print(path)
else:
print(path, end=" ")
print()

# Print directories
for path in args.paths:
if os.path.isdir(path):

if len(args.paths) > 1:
print(f"\n{path}:")

files = get_files(path)

if args.one:
for file in files:
print(file)
else:
print(" ".join(files))
54 changes: 54 additions & 0 deletions implement-shell-tools/wc/wc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import argparse

parser = argparse.ArgumentParser(prog="wc")
parser.add_argument("-l", action="store_true", help="Count lines")
parser.add_argument("-w", action="store_true", help="Count words")
parser.add_argument("-c", action="store_true", help="Count bytes")
parser.add_argument("files", nargs="+")

args = parser.parse_args()


def format_counts(lines, words, chars):
if not args.l and not args.w and not args.c:
return f"{lines:8}{words:8}{chars:8}"

output = ""

if args.l:
output += f"{lines:8}"
if args.w:
output += f"{words:8}"
if args.c:
output += f"{chars:8}"

return output


total_lines = 0
total_words = 0
total_chars = 0

for file in args.files:
with open(file, "r") as f:
text = f.read()

lines = text.count("\n")

stripped = text.strip()
words = len(stripped.split()) if stripped else 0

chars = len(text.encode())

total_lines += lines
total_words += words
total_chars += chars

print(format_counts(lines, words, chars), file)


if len(args.files) > 1:
print(
format_counts(total_lines, total_words, total_chars),
"total"
)
Loading