Python cut.py

提供:onayami
2025年3月28日 (金) 21:29時点におけるMoutaku3dayo (トーク | 投稿記録)による版
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
import argparse
import sys

def cut(fields, delimiter, input_file):
    """
    Extract specified fields or columns from the input file or standard input.

    :param fields: Comma-separated list of fields to extract (1-based indexing).
    :param delimiter: Delimiter used to separate fields.
    :param input_file: Input file path or None for standard input.
    """
    # Parse the fields to extract
    try:
        field_indices = [int(f) - 1 for f in fields.split(",")]
    except ValueError:
        print("Error: Fields must be integers.", file=sys.stderr)
        sys.exit(1)

    # Open the input file or use standard input
    input_source = open(input_file, "r") if input_file else sys.stdin

    try:
        for line in input_source:
            # Split the line using the specified delimiter
            parts = line.rstrip().split(delimiter)

            # Extract the specified fields and print them
            try:
                output = delimiter.join([parts[i] for i in field_indices])
                print(output)
            except IndexError:
                print("Error: Field index out of range.", file=sys.stderr)
    finally:
        if input_file:
            input_source.close()

def main():
    parser = argparse.ArgumentParser(description="Python implementation of the cut command.")
    parser.add_argument("-f", "--fields", required=True, help="Comma-separated list of fields to extract (1-based indexing).")
    parser.add_argument("-d", "--delimiter", default="\t", help="Delimiter used to separate fields (default: tab).")
    parser.add_argument("-i", "--input", help="Input file path (default: standard input).")

    args = parser.parse_args()

    cut(fields=args.fields, delimiter=args.delimiter, input_file=args.input)

if __name__ == "__main__":
    main()


関連項目