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

args = sys.argv[1:]

show_line_numbers = "-n" in args
number_non_empty = "-b" in args

files = [arg for arg in args if arg not in ["-n", "-b"]]

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

if number_non_empty:
count = 1
for line in lines:
if line.strip() != "":
print(f"{count:6} {line}", end="")
count += 1
else:
print(line, end="")

elif show_line_numbers:
for i, line in enumerate(lines, start=1):
print(f"{i:6} {line}", end="")

else:
print("".join(lines), end="")
28 changes: 28 additions & 0 deletions implement-shell-tools/ls/ls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import os
import sys

args = sys.argv[1:]

show_all = "-a" in args
one_per_line = "-1" in args

paths = [arg for arg in args if arg not in ["-a", "-1"]]

if not paths:
paths = ["."]

for path in paths:
items = os.listdir(path)

if show_all:
items.sort()
items = [".", ".."] + items
else:
items = [item for item in items if not item.startswith(".")]
items.sort()

if one_per_line:
for item in items:
print(item)
else:
print(" ".join(items))
44 changes: 44 additions & 0 deletions implement-shell-tools/wc/wc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import sys

args = sys.argv[1:]

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

files = [arg for arg in args if arg not in ["-l", "-w", "-c"]]

total_lines = 0
total_words = 0
total_chars = 0

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

lines = len(content.splitlines())
words = len(content.split())
chars = len(content)

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

if show_lines:
print(lines, file)
elif show_words:
print(words, file)
elif show_chars:
print(chars, file)
else:
print(lines, words, chars, file)

if len(files) > 1:
if show_lines:
print(total_lines, "total")
elif show_words:
print(total_words, "total")
elif show_chars:
print(total_chars, "total")
else:
print(total_lines, total_words, total_chars, "total")