#!/usr/bin/env python import sys import getopt def usage(): print """Will generate generic sql inserts from a tab delimited input read from stdin. Usage: %s [OPTIONS] Options: -t table, --table=table The table part of the SQL. -f field,idx, --field=field,idx Maps the field with idx idx to the field name field. -d delimiter, --delimiter=delimiter Sets the field delimiter in the input. Defaults to a tab (\\t). """ % (sys.argv[0]) def sqlize(line_fields): global table, fields, maps ret = "INSERT INTO %s" % table +" ("+ fields +") VALUES (" values = "" for idx in maps: values += "'%s'," % line_fields[idx] values = values[:-1] ret += values + ")" return ret try: opts, args = getopt.getopt(sys.argv[1:], "t:f:d:h", ["table=", "field=", "delimiter=", "help"]) except getopt.GetoptError: usage() sys.exit(2) table = None delimiter = "\t" fields = [] maps = [] for o,a in opts: if o in ("-h", "--help"): usage() elif o in ("-f", "--fields"): pairs = a.split(",") fields.append(pairs[0]) maps.append(int(pairs[1])) elif o in ("-t", "--table"): table = a elif o in ("-d", "--delimiter"): delimiter = a if table == None: usage() sys.exit(2) fields = ",".join(fields) for line in sys.stdin.readlines(): print sqlize(line.rstrip("\n\r").split(delimiter))