diff --git a/implement-shell-tools/cat/cat.py b/implement-shell-tools/cat/cat.py new file mode 100644 index 000000000..05d819234 --- /dev/null +++ b/implement-shell-tools/cat/cat.py @@ -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="") \ No newline at end of file diff --git a/implement-shell-tools/ls/ls.py b/implement-shell-tools/ls/ls.py new file mode 100644 index 000000000..fbfdf71e9 --- /dev/null +++ b/implement-shell-tools/ls/ls.py @@ -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)) \ No newline at end of file diff --git a/implement-shell-tools/wc/wc.py b/implement-shell-tools/wc/wc.py new file mode 100644 index 000000000..1a62e5748 --- /dev/null +++ b/implement-shell-tools/wc/wc.py @@ -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") \ No newline at end of file