diff --git a/implement-shell-tools/cat/cat.py b/implement-shell-tools/cat/cat.py new file mode 100644 index 000000000..86ac77656 --- /dev/null +++ b/implement-shell-tools/cat/cat.py @@ -0,0 +1,33 @@ +import argparse + + +parser = argparse.ArgumentParser( + prog="cat implemnet by Python" +) + +parser.add_argument("-n", action="store_true") +parser.add_argument("-b", action="store_true") +parser.add_argument("files", nargs="+") + +args = parser.parse_args() + +line_number = 1 + +for filename in args.files: + try: + with open(filename) as file: + for line in file: + line = line.rstrip("\n") + + if args.b and line == "": + print() + continue + + if args.n or args.b: + print(f"{line_number} {line}") + line_number += 1 + else: + print(line) + + except FileNotFoundError: + print(f"{filename}: No such file or directory") \ 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..8cb119fbf --- /dev/null +++ b/implement-shell-tools/ls/ls.py @@ -0,0 +1,36 @@ +import argparse +import os + +parser = argparse.ArgumentParser( + prog="ls implemnet by Python" +) + +parser.add_argument("-1", action="store_true", dest="one_per_line") +parser.add_argument("-a", action="store_true", dest="show_all") +parser.add_argument("paths", nargs="*") + +args = parser.parse_args() + +if not args.paths: + args.paths = ["."] + +for path in args.paths: + if os.path.isdir(path): + files = sorted(os.listdir(path)) + + if not args.show_all: + files = [file for file in files if not file.startswith(".")] + + if args.one_per_line: + for file in files: + print(file) + else: + for file in files: + print(file, end=" ") + print() + + elif os.path.isfile(path): + print(path) + + else: + print(f"{path}: No such file or directory") \ 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..1b4ca7d48 --- /dev/null +++ b/implement-shell-tools/wc/wc.py @@ -0,0 +1,51 @@ +import argparse + + +parser = argparse.ArgumentParser() + +parser.add_argument("-l", action="store_true") +parser.add_argument("-w", action="store_true") +parser.add_argument("-c", action="store_true") +parser.add_argument("files", nargs="+") + +args = parser.parse_args() + + +def add_count(output, value): + output.append(str(value)) + + +total_lines = 0 +total_words = 0 +total_bytes = 0 + +for filename in args.files: + + with open(filename, "rb") as file: + content = file.read() + + lines = content.count(b"\n") + words = len(content.split()) + bytes_count = len(content) + + total_lines += lines + total_words += words + total_bytes += bytes_count + + if not args.l and not args.w and not args.c: + print(f"{lines:8} {words:8} {bytes_count:8} {filename}") + + else: + output = [] + + if args.l: + add_count(output, lines) + + if args.w: + add_count(output, words) + + if args.c: + add_count(output, bytes_count) + + print(f"{' '.join(output):>8} {filename}") +