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
40 changes: 40 additions & 0 deletions implement-shell-tools/cat/cat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import sys

args = sys.argv[1:]

show_n = "-n" in args
show_b = "-b" in args

files = [arg for arg in args if not arg.startswith("-")]

content = ""

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

lines = content.split("\n")

if lines and lines[-1] == "":
lines.pop()

output = []

if show_n:
for i, line in enumerate(lines, start=1):
output.append(f"{str(i).rjust(6)} {line}")

elif show_b:
count = 1

for line in lines:
if line != "":
output.append(f"{str(count).rjust(6)} {line}")
count += 1
else:
output.append("")

else:
output = lines

print("\n".join(output))
22 changes: 22 additions & 0 deletions implement-shell-tools/ls/ls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import os
import sys

args = sys.argv[1:]

show_all = "-a" in args

directory = "."

for arg in args:
if not arg.startswith("-"):
directory = arg

files = sorted(os.listdir(directory))

if show_all:
files = [".", ".."] + files
else:
files = [file for file in files if not file.startswith(".")]

for file in files:
print(file)
72 changes: 72 additions & 0 deletions implement-shell-tools/wc/wc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import sys

args = sys.argv[1:]

show_lines = "-l" in args
show_words = "-w" in args
show_bytes = "-c" in args

files = [arg for arg in args if not arg.startswith("-")]

def get_stats(text):
return {
"lines": text.count("\n"),
"words": len(text.split()),
"bytes": len(text.encode("utf-8"))
}

def format_num(num):
return str(num).rjust(8)

total_lines = 0
total_words = 0
total_bytes = 0

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

stats = get_stats(content)

total_lines += stats["lines"]
total_words += stats["words"]
total_bytes += stats["bytes"]

output = []

if show_lines:
output.append(format_num(stats["lines"]))
elif show_words:
output.append(format_num(stats["words"]))
elif show_bytes:
output.append(format_num(stats["bytes"]))
else:
output.extend([
format_num(stats["lines"]),
format_num(stats["words"]),
format_num(stats["bytes"])
])

output.append(file)

print(" ".join(output))

if len(files) > 1:
output = []

if show_lines:
output.append(format_num(total_lines))
elif show_words:
output.append(format_num(total_words))
elif show_bytes:
output.append(format_num(total_bytes))
else:
output.extend([
format_num(total_lines),
format_num(total_words),
format_num(total_bytes)
])

output.append("total")

print(" ".join(output))
Loading