0

I am trying to search in a .sql file for sql statement which starts with CREATE TABLE followed by fields values then keywords [TB_DATA and TB_INDX] and ends by ;

Like

CREATE TABLE HDTB_CODE (IDPK VARCHAR(256) NOT NULL) IN TB_DATA INDEX IN TB_INDX;

.sql file statement is in multiple lines

CREATE TABLE HDTB_CODE
(
IDPK VARCHAR(256) NOT NULL
)
IN TB_DATA
INDEX IN TB_INDX;

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

-------------output----------------------

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;

2 Answers 2

1

Try this:

use strict;
use warnings;

my $filename = 'somefile.sql';
open(my $fh, '<', $filename) || die "unable to open '$filename' for read; $!";

local $/ = "";     # Paragraph mode
while (<$fh>) {
    if (/^CREATE TABLE.+TB_DATA.+TB_INDX/s) {
        print   # or do something else
    }
}

close $fh;

The use of an empty string in $/ marks "paragraph mode", which means the record separator is two (or more) new-lines, so it breaks on the blank lines (if that is not the case, then you could use ";\n").

The s modifier after the regular expression is required for . to match new-lines.

Sign up to request clarification or add additional context in comments.

2 Comments

what if there is no newline. how to use it as Paragraph mode
Sorry for the delay, I have been away. If there is no newline then pick something else for the record seperator. $/ can be set to just about anything, paragraph mode is just a convienient short-cut (comes from awk).
0
use strict;
use warnings;

$/ = '';
print grep { $_ =~ /CREATE TABLE/ && $_ =~ /INDEX/} <>;

Or:

$/ = '';
print grep { /^CREATE TABLE.+TB_DATA.+TB_INDX/s} <>;

Usage:

script_name.pl sql_file

2 Comments

Not without the s modifier.
It is splited into two regex, so it works. One regex will indeed need the s modifier.I added a second option though, with your nice regex :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.