0

我正在尝试在 .sql 文件中搜索以 CREATE TABLE 开头的 sql 语句,然后是字段值,然后是关键字 [TB_DATA 和 TB_INDX],并以 ; 结尾。它在多行

.sql 文件语句在多行中

-- CREATE TABLE HDTB_COD;
CREATE TABLE HDTB_CODE( IDPK VARCHAR(256) NOT NULL)

IN TB_DATA INDEX 
IN TB_INDX;

CREATE TABLE HDTB_RES
(ARTID VARCHAR(256) NOT NULL)
IN TB_DATA INDEX 
IN TB_INDX;
-- DROP TABLE HDTB_COD;
CREATE TABLE HDTB_DE ( IDPK VARCHAR(256) 
NOT NULL); 

- - - - - - -输出 - - - - - - - - - - -

CREATE TABLE HDTB_CODE( IDPK VARCHAR(256) NOT NULL)

IN TB_DATA INDEX IN TB_INDX;

CREATE TABLE HDTB_RES(ARTID VARCHAR(256) NOT NULL)

IN TB_DATA INDEX IN TB_INDX;
4

2 回答 2

1
perl -n -e 'chomp; next if (/^--/);@p=() if /CREATE TABLE/; push @p,$_; if (/IN TB_DATA INDEX IN TB_INDX;/) { print "@p\n"; }' t.sql

这个怎么运作

chomp; # remove newlines
next if (/^--/);  #skip lines that are SQL comments
@p = () if /CREATE TABLE/; #start of a table definition, clear array @p
push @p, $_; # put current line into array @p
#condition found, print @p    
if (/IN TB_DATA INDEX IN TB_INDX;/) { print "@p\n"; }
于 2013-05-17T08:50:01.747 回答
0

下面是一个如何创建快速而肮脏的解析管道的示例。一旦您了解了基本模式,就很容易添加更多过滤步骤(with grep)或转换步骤(with map

# Slurp entire file.
my $sql = do { local $/ = undef; <> };

# 1. Grab the CREATE TABLE statements.
# 2. Retain only the statements of interest.
# 3. Modify the statements as needed before printing.
print
    map  { "$_\n" }                         # 3b. Add trailing newlines.
    map  { s/\s+/ /g; $_ }                  # 3a. Normalize whitespace.
    grep { /IN TB_INDX/ }                   # 2b. Filter.
    grep { /IN TB_DATA INDEX/ }             # 2a. Filter.
    $sql =~ /^(CREATE TABLE .+?;)\s*$/gsm;  # 1.  Grab.
于 2013-05-17T11:52:28.100 回答