1

I have test file with the below contents:

CREATE TABLE XYZ (
ABC INT,
CDE CHAR(10),
.
.
.
);
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);
CREATE TABLE XYZ_1 (
ABC INT,
CDE CHAR(10),
.
.
.
);
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);

Now I want to split this test single file into 2 files: one file with CREATE statement till ; as file1 and the other file as file2 with REPLACE statement till ;.

Can you help me with how to split this, please?

  • Are these separated by \n s ? your previous post showed them all on the same line. Also, do you have "Similarly" in the input file ? – jai_s Feb 2 '16 at 11:08
2

Here's one way with sed:

sed -n 'H                      # append every line to hold buffer
/CREATE\|REPLACE/h             # if CREATE or REPLACE, overwrite hold buffer
/;/{                           # if line matches ; then
x                              # exchange hold space w. pattern space
/CREATE/w file1                # if pattern space matches CREATE, write to file1
/REPLACE/w file2               # if it matches REPLACE, write it to file2
}
' infile
1

Try this awk script:

/CREATE/{
b="";
    while (match($0, ";$")==0)
    {
        b=b $0"\n";
        getline;

    }
    b=b $0;
    print b > "file1";
}

/REPLACE/{
c="";
    while (match($0, ";$")==0)
    {
        c=c $0"\n";
        getline;

    }
    c=c $0;
    print c > "file2";
}

So

awk -f some.awk inputFile

produces:

cat file1
CREATE TABLE XYZ (
ABC INT,
CDE CHAR(10),
.
.
.
);
CREATE TABLE XYZ_1 (
ABC INT,
CDE CHAR(10),
.
.
.
);

and

cat file2
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);
1
sed -e '/CREATE/,/;/s/^//w file1' -e//d <infile >file2

... that just negates the range. It writes all of the lines within the CREATE ... ; span to file1 and all others to file2.

More simply, maybe:

sed -ne '/CREATE/,/;/w file1' -e '/REPLACE/,/;/w file2' <infile

...though that one might overlap if your actual input isnt as cut and dry as your example data.

With your example data, however, I can run either command and afterward do:

head -n50 file[12]

...to produce the following output:

==> file1 <==
CREATE TABLE XYZ (
ABC INT,
CDE CHAR(10),
.
.
.
);
CREATE TABLE XYZ_1 (
ABC INT,
CDE CHAR(10),
.
.
.
);

==> file2 <==
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);
Similarly, REPLACE VIEW XYZ (
ABC,
CDE,
EFG
);
  • 1
    @don_crissti - that's why i offered two - the best way, i think, would be both - only write to file2 after deleting lines which wrote to file1 and are within a replace block. divide and conquer? – mikeserv Feb 4 '16 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.