#!/usr/bin/env python

import argparse
import errno
from itertools import count, islice
try:
    from itertools import izip_longest
except ImportError:
    from itertools import zip_longest as izip_longest
import sys


def string_escape(x):
    try:
        return bytes(x, encoding="utf-8").decode("unicode_escape")
    except TypeError:
        return x.decode("string_escape")


def indexed_field(idx):
    def inner(i, N, n, f):
        return i == idx or i == N+idx+1
    return inner


def range_field(start, stop):
    def inner(i, N, n, f):
        return start <= i <= stop
    return inner


def every_nth_field(start, step):
    def inner(i, N, n, f):
        return i >= start and (i - start) % step == 0
    return inner


def name_field(name):
    def prefix(i, N, n, f):
        return n.startswith(name[:-1])
    def suffix(i, N, n, f):
        return n.endswith(name[1:])
    def exact(i, N, n, f):
        return n == name

    if name[-1] == "*":
        return prefix
    elif name[0] == "*":
        return suffix
    else:
        return exact


def field_factory(f):
    # Is it an integer
    try:
        return indexed_field(int(f))
    except ValueError:
        pass

    # Is it a range
    try:
        r = f.split("-")
        if len(r) == 2:
            if r[1] == "":
                r[1] = 10**6  # represents integer infinity
            return range_field(*list(map(int, r)))
    except ValueError:
        pass

    # Is it an every nth field
    try:
        r = f.split("::")
        if len(r) == 2:
            if r[0] == "":
                r[0] = 1
            return every_nth_field(*list(map(int, r)))
    except ValueError:
        pass

    # Assume it is a name field
    return name_field(f)


def fields_type(fields):
    return list(map(field_factory, fields.split(",")))


def _lines():
    """Return the next line from stdin but return the first line twice"""
    # Special care for the firstline
    l = sys.stdin.readline()
    if l != "":
        yield l

    # Do while loop
    while l != "":
        yield l
        l = sys.stdin.readline()


def split(delimiter, line):
    return line.strip().split(delimiter)


def project(wanted_fields, field_names, fields):
    def _zip(*args):
        return islice(izip_longest(*args), len(args[-1]))
    return [
        f
        for wf in wanted_fields
        for i, n, f in _zip(count(1), field_names, fields)
        if wf(i, len(fields), n, f)
    ]


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="An unbuffered watered down clone of cut"
    )

    parser.add_argument(
        "--fields", "-f",
        type=fields_type,
        help="Select only those fields",
        default="1"
    )
    parser.add_argument(
        "--delimiter", "-d",
        type=string_escape,
        default="\t",
        help="Use DELIMITER instead of TAB for field delimiter"
    )

    args = parser.parse_args(sys.argv[1:])

    try:
        lines = _lines()
        field_names = split(args.delimiter, next(lines))
        for line in lines:
            fields = split(args.delimiter, line)
            sys.stdout.write(args.delimiter.join(
                project(args.fields, field_names, fields)
            ) + "\n")
            sys.stdout.flush()
    except KeyboardInterrupt:
        pass
    except IOError as e:
        if e.errno != errno.EPIPE:
            raise
