Python uniq.py

提供:onayami
import argparse
import sys

def uniq(count, input_file):
    """
    Filter out adjacent duplicate lines from input and optionally count occurrences.

    :param count: If True, prefix lines by the number of occurrences.
    :param input_file: Input file path or None for standard input.
    """
    # Open the input file or use standard input
    input_source = open(input_file, "r") if input_file else sys.stdin

    try:
        previous_line = None
        count_occurrences = 0

        for line in input_source:
            line = line.rstrip()  # Remove trailing newline characters

            if line == previous_line:
                count_occurrences += 1
            else:
                if previous_line is not None:
                    if count:
                        print(f"{count_occurrences} {previous_line}")
                    else:
                        print(previous_line)

                previous_line = line
                count_occurrences = 1

        # Handle the last line
        if previous_line is not None:
            if count:
                print(f"{count_occurrences} {previous_line}")
            else:
                print(previous_line)

    finally:
        if input_file:
            input_source.close()

def main():
    parser = argparse.ArgumentParser(description="Python implementation of the uniq command.")
    parser.add_argument("-c", "--count", action="store_true", help="Prefix lines by the number of occurrences.")
    parser.add_argument("-i", "--input", help="Input file path (default: standard input).")

    args = parser.parse_args()

    uniq(count=args.count, input_file=args.input)

if __name__ == "__main__":
    main()


関連項目