#!/usr/bin/env python # Exercise 9 # sed command import re import sys import argparse from pathlib import Path def parse(expression): try: match = re.fullmatch(r's/(.*)/(.*)/(g{0,1})', expression) count = 0 if match.group(3) == "g" else 1 return { "rgx": re.compile(match.group(1)), "rep": match.group(2), "n": count } except Exception: print(f"sed: expresión «{expression}» inválida") sys.exit(1) parser = argparse.ArgumentParser() parser.add_argument("stream", default=sys.stdin, nargs="*") parser.add_argument( "-e", "--expression", required=True, type=str, action="append" ) args = parser.parse_args() res = "" for exp in args.expression: exp = parse(exp) for stream in args.stream: if isinstance(args.stream, list): stream = Path(stream).read_text() else: stream = stream.strip() if res == "": res = stream res = re.sub(exp["rgx"], exp["rep"], res, count=exp["n"]) print(res)