我如何在导入过程中 运行 过滤 pg_dump 数据?
How do I run a filter on pg_dump data during an import?
在 Mac OSX (iTerm2) 上使用终端,除 postgres 外没有任何外部应用程序,我想 运行 一些正则表达式 find/replaces 在相当大的 ( 52 MB) pg_dump 数据文件,因为它被导入到 PostgreSQL 数据库中。我需要在转储文件到达 PostgreSQL 之前执行此操作,因为我必须转换传入的 SQL 创建和修改表的查询。
我用来导入数据的 shell 命令是:
psql MyDatabase < mydata.sql
有没有办法通过正则表达式 find/replace 过滤器传输数据?我可以使用 grep 等本机 Linux 命令行实用程序做一些事情吗?
或者,我如何批量处理我的正则表达式并将它们应用到我的转储文件,然后将更改保存到新文件?
您可以使用理解正则表达式的sed
。
例如,要用 "anotherschema" 替换所有出现的被单词边界包围的 "myschema",您可以使用:
sed -e 's/\bmy\(schema\)\b/another/g' mydata.sql | psql MyDatabase
Alternatively, how would I batch my regex's and apply them to my dump
file and then save the changes to a new file?
sed -e 's/\bmy\(schema\)\b/another/g' mydata.sql >mysqlnew.sql
这会将输出重定向到名为 mysqlnew.sql
.
的新文件
请注意 sed
支持就地编辑选项。使用就地编辑 -i
选项,上面的命令可以替换为
sed -i.bak -e 's/\bmy\(schema\)\b/another/g' mydata.sql
此命令将原始 mydata.sql
复制到 mydata.sql.bak
并
将更改永久写入 mydata.sql
.
在 Mac OSX (iTerm2) 上使用终端,除 postgres 外没有任何外部应用程序,我想 运行 一些正则表达式 find/replaces 在相当大的 ( 52 MB) pg_dump 数据文件,因为它被导入到 PostgreSQL 数据库中。我需要在转储文件到达 PostgreSQL 之前执行此操作,因为我必须转换传入的 SQL 创建和修改表的查询。
我用来导入数据的 shell 命令是:
psql MyDatabase < mydata.sql
有没有办法通过正则表达式 find/replace 过滤器传输数据?我可以使用 grep 等本机 Linux 命令行实用程序做一些事情吗?
或者,我如何批量处理我的正则表达式并将它们应用到我的转储文件,然后将更改保存到新文件?
您可以使用理解正则表达式的sed
。
例如,要用 "anotherschema" 替换所有出现的被单词边界包围的 "myschema",您可以使用:
sed -e 's/\bmy\(schema\)\b/another/g' mydata.sql | psql MyDatabase
Alternatively, how would I batch my regex's and apply them to my dump file and then save the changes to a new file?
sed -e 's/\bmy\(schema\)\b/another/g' mydata.sql >mysqlnew.sql
这会将输出重定向到名为 mysqlnew.sql
.
请注意 sed
支持就地编辑选项。使用就地编辑 -i
选项,上面的命令可以替换为
sed -i.bak -e 's/\bmy\(schema\)\b/another/g' mydata.sql
此命令将原始 mydata.sql
复制到 mydata.sql.bak
并
将更改永久写入 mydata.sql
.