使用 shell 脚本从脚本中选择所需的 sql

selecting required sql from script using shell scripting

我有一个包含许多 table 的 ddl 的 sybase ddl 文件.. 但问题在于 ddl 还有很多其他的东西和不必要的索引创建脚本和注释。有没有办法从这个文件中只提取 ddl。下面是一个小文件示例。

-------------------------------------------
-- DDL fpr table 'prod.dbo.tbl1'
--------------------------------------------
print '<<<< creating table prod.dbo.tbl1
go
setuser 'dbo'
go

create table tbl1 (id numeric (10,0),
                     etity     CHAR(2))

-------------------------------------------
-- DDL fpr table 'prod.dbo.tbl2'
--------------------------------------------
print '<<<< creating table prod.dbo.tbl1
go
setuser 'dbo'
go

create table tbl2 (id numeric (10,0),
                     etity     CHAR(2))
---------------------------------------------------

从这个文件我只想要创建 table ddl。有什么办法可以实现吗..输出应该只是像下面这样的DDL..

create table tbl1 id numeric (10,0),
                     etity     CHAR(2);
create table tbl2 id numeric (10,0),
                     etity     CHAR(2);

如果所有不需要的行都以此字符开头:--, print, go, setuser, ...

你可以这样做:

cat DDL.txt | egrep -v '^--|^print|^go|^setuser'

假设:

  • 只对 create table 命令感兴趣(即,对其他 table 相关的 DDL 不感兴趣,例如 create index、RI/check 约束、default/rule 绑定、缓存配置,grant/revoke,等等)
  • a create table 块通过空行(无空格)、go(从第 1 列开始)或注释块(-- 从第 1 列开始)终止

示例输入文件:

$ cat ddl.sql
-------------------------------------------
-- DDL fpr table 'prod.dbo.tbl1'
--------------------------------------------
print '<<<< creating table prod.dbo.tbl1
go
setuser 'dbo'
go

create table tbl1 (id numeric (10,0),
                     etity     CHAR(2))

-------------------------------------------
-- DDL fpr table 'prod.dbo.tbl2'
--------------------------------------------
print '<<<< creating table prod.dbo.tbl1
go
setuser 'dbo'
go

create table tbl2 (id numeric (10,0),
                     etity     CHAR(2))
---------------------------------------------------

create table tbl3 (id numeric (10,0),
                     etity     CHAR(2))
go
---------------------------------------------------

一个awk解法:

awk '
/create table/         { printme=1 }     # set our "print" flag when we see "create table"
/^$/ || /^go/ || /^--/ { if (printme)    # if in midst of printing "create table" then 
                            print ";"    # print ending ";" and then
                         printme=0       # clear "print" flag
                       }
printme' ddl.sql                         # if "print" flag is set (ie, "=1") then print current line

或者作为删除评论的单行:

awk '/create table/ {printme=1} /^$/ || /^go/ || /^--/ { if (printme) print ";";printme=0} printme' ddl.sql

运行 以上针对我的 ddl.sql 生成:

create table tbl1 (id numeric (10,0),
                     etity     CHAR(2))
;
create table tbl2 (id numeric (10,0),
                     etity     CHAR(2))
;
create table tbl3 (id numeric (10,0),
                     etity     CHAR(2))
;

注意: 如果 OP 需要在行尾添加 ; 结尾,则可以向 awk 解决方案添加更多代码...