import sys import re if len(sys.argv) < 4: print("Expected: ./extract_db.py [sql file name] [database name] [new file name]") sys.exit(-1) with open(sys.argv[1], 'rb') as f_in: create_db = re.compile(bytes("CREATE DATABASE .*?`{}`".format(sys.argv[2]), encoding='utf-8')) create_stmt = re.compile(bytes("CREATE DATABASE", encoding='utf-8')) in_section = False line_count = 0 with open(sys.argv[3], 'wb') as f_out: for line in f_in: if not in_section: if create_db.match(line): print("Found the section where the db def starts") in_section = True f_out.write(line) line_count += 1 else: if not create_stmt.match(line): f_out.write(line) line_count += 1 else: print("Cut out {} lines that define the {} database.".format(line_count, sys.argv[2])) f_out.close() f_in.close() sys.exit(0) print("Wasn't able to find a definition for a database of that name")