diff --git a/implement-shell-tools/cat/cat.py b/implement-shell-tools/cat/cat.py new file mode 100644 index 000000000..5c62e9243 --- /dev/null +++ b/implement-shell-tools/cat/cat.py @@ -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)) diff --git a/implement-shell-tools/ls/ls.py b/implement-shell-tools/ls/ls.py new file mode 100644 index 000000000..a7c98d200 --- /dev/null +++ b/implement-shell-tools/ls/ls.py @@ -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) diff --git a/implement-shell-tools/wc/wc.py b/implement-shell-tools/wc/wc.py new file mode 100644 index 000000000..26fe10e15 --- /dev/null +++ b/implement-shell-tools/wc/wc.py @@ -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))