【发布时间】:2015-11-25 13:30:22
【问题描述】:
我有一个 sql nodata 转储,我需要通过它并替换每个 create table 查询的引擎部分。我被卡住的地方是我需要在每个要替换的字符串中为相应的表提及表名
假设文件如下
CREATE TABLE `tablename1` (
-- #columns and keys
) ENGINE=InnoDB AUTO_INCREMENT=5075 DEFAULT CHARSET=utf8;
CREATE TABLE `tablename2` (
-- #columns and keys
) ENGINE=something AUTO_INCREMENT=55 DEFAULT CHARSET=latin1;
想要的结果是:
CREATE TABLE `tablename1` (
-- #columns and keys
) ENGINE=-myreplacedstring/tablename1; -- #table name 1 is appended to this line
CREATE TABLE `tablename2` (
-- #columns and keys
) ENGINE=myreplacedstring/tablename2; -- #table name 2 is appended to this line
我试过了
fin = open('dump.sql','r')
filedata = fin.read()
fin.close()
newdata = re.sub('(?<=ENGINE).*;', '-myreplacedstring-', filedata)
fout = open('fed_dump.sql','w')
fout.write(newdata)
fout.close()
但这只是将字符串替换为固定字符串,无论它是哪个表。
我也尝试逐行处理,以便每次通过时都能获取表名,但我不知道如何继续。
with open('dump.sql') as infile, open('dump_fed.sql', 'w') as outfile:
for line in infile:
#tablename= if line contains create table, update tablename, else do nothing
line = re.sub('(?<=ENGINE).*;', '-myreplacedstring-'+tablename, line)
outfile.write(line)
我被困在如何将每个表的表名放入替换的字符串中。任何帮助表示赞赏。
【问题讨论】:
-
如果您将整个文件作为一个字符串读取(如果它不大),我建议将
CREATE TABLE和) ENGINE=之间的所有子字符串抓取到一些 table_block 中(您可以使用此正则表达式 -CREATE\s+TABLE\s+`[^`]*`\s+\([^)]*(?:\)(?!\s+ENGINE=)[^)])*\)\s+ENGINE=.*(demo here),然后使用re.sub(r"\bENGINE\b.*", "ENGINE-myreplacedstring-", table_block)。 -
我遇到的问题是将表名添加到每个表的 myreplacedstring 的末尾
标签: python regex federated-storage-engine