202309041808_Kindle Clippings

#!/usr/bin/env python3

import logging
import argparse
import re


def process(args):
    with open(args.file, "r", encoding="utf-8") as f:
        lines = f.readlines()

    is_title = True
    is_relevant = False
    content = []

    for line in lines:
        if line.startswith("==="):
            is_title = True
            is_relevant = False
            continue

        if is_title:
            is_title = False
            if re.search(args.pattern, line):
                is_relevant = True
                content.append("=====\n" + line)
        elif is_relevant:
            content.append(line)

    print("".join(content))


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    parser = argparse.ArgumentParser()
    parser.add_argument("--file", action="store", type=str, required=True)
    parser.add_argument("--pattern", action="store", type=str, required=True)

    args = parser.parse_args()
    logging.info(f"Arguments: {args!r}")

    process(args)