|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Deduplicate configuration lines while preserving sorted unique output. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + python dedup_config.py -i api_config_0_size.txt |
| 6 | + python dedup_config.py -i api_config_0_size.txt -o /output/dir/dedup.txt |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +import os |
| 13 | + |
| 14 | + |
| 15 | +def parse_args(): |
| 16 | + parser = argparse.ArgumentParser( |
| 17 | + description="Deduplicate configuration lines while preserving sorted unique output.", |
| 18 | + ) |
| 19 | + parser.add_argument("-i", "--input", required=True, help="Input config file path") |
| 20 | + parser.add_argument( |
| 21 | + "-o", |
| 22 | + "--output", |
| 23 | + default=None, |
| 24 | + help="Output file path. Default: <input_stem>_dedup.txt in same dir as input", |
| 25 | + ) |
| 26 | + return parser.parse_args() |
| 27 | + |
| 28 | + |
| 29 | +def main(): |
| 30 | + args = parse_args() |
| 31 | + |
| 32 | + input_path = args.input |
| 33 | + if args.output: |
| 34 | + output_path = args.output |
| 35 | + else: |
| 36 | + stem, ext = os.path.splitext(input_path) |
| 37 | + output_path = f"{stem}_dedup{ext}" |
| 38 | + |
| 39 | + output_dir = os.path.dirname(output_path) |
| 40 | + if output_dir: |
| 41 | + os.makedirs(output_dir, exist_ok=True) |
| 42 | + |
| 43 | + seen = set() |
| 44 | + total = 0 |
| 45 | + with open(input_path, encoding="utf-8") as f: |
| 46 | + for line in f: |
| 47 | + total += 1 |
| 48 | + seen.add(line.rstrip("\n")) |
| 49 | + |
| 50 | + unique_lines = sorted(seen) |
| 51 | + |
| 52 | + with open(output_path, "w", encoding="utf-8") as f: |
| 53 | + for line in unique_lines: |
| 54 | + f.write(line + "\n") |
| 55 | + |
| 56 | + print(f"Total lines: {total}") |
| 57 | + print(f"Unique lines: {len(unique_lines)}") |
| 58 | + print(f"Duplicates: {total - len(unique_lines)}") |
| 59 | + print(f"Output: {output_path}") |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + main() |
0 commit comments