1

I have a file with the below contents. All I need to do is filter the ALTER script that has UNIQUE keyword in it and move it to a different file. I tried using sed -n '/ALTER TABLE/,/UNIQUE("ID");/p' file. But it didn't work.

ALTER TABLE RELEASE.ACL_ENTRY
            ADD CONSTRAINT RELEASE.FK5111A
            FOREIGN KEY( ACL_OID )
            REFERENCES RELEASE.ACL ( OID )
            ON DELETE CASCADE
            --ON UPDATE NO ACTION ;
    ALTER TABLE RELEASE.ACTION_DESC
            ADD CONSTRAINT RELEASE.UN2160A
            UNIQUE( ID_MASK ) ;
    ALTER TABLE RELEASE.ACTION_DESC
            ADD CONSTRAINT RELEASE.UN2160B
            UNIQUE( NAME ) ;
    ALTER TABLE RELEASE.ACTION_DESC_LOD
            ADD CONSTRAINT RELEASE.FK2170
            FOREIGN KEY( ACTION_DESC_OID )
            REFERENCES RELEASE.ACTION_DESC ( OID )
            ON DELETE CASCADE
            --ON UPDATE NO ACTION ;
    ALTER TABLE RELEASE.ACTION_SET
            ADD CONSTRAINT RELEASE.UN2120A
            UNIQUE( "ID" ) ;
    ALTER TABLE RELEASE.ACTION_SET
            ADD CONSTRAINT RELEASE.UN2120B
            UNIQUE( NAME ) ;
    ALTER TABLE RELEASE.ACTION_SET_LOD
            ADD CONSTRAINT RELEASE.FK2150A
            FOREIGN KEY( ACTION_SET_OID )
            REFERENCES RELEASE.ACTION_SET ( OID )
            ON DELETE CASCADE
            --ON UPDATE NO ACTION ;
    ALTER TABLE RELEASE.APP_DESC
            ADD CONSTRAINT RELEASE.FK20A
            FOREIGN KEY( WEB_MOD_OID )
            REFERENCES RELEASE.WEB_MOD ( OID )
            ON DELETE CASCADE
            --ON UPDATE NO ACTION ;
    ALTER TABLE RELEASE.APP_DESC
            ADD CONSTRAINT RELEASE.CC20B
            CHECK( ( WEB_MOD_OID IS NOT NULL ) AND ( WEB_MOD_SL IS NULL )  ) ;

The output should be like the below contents in a different file.

ALTER TABLE RELEASE.ACTION_DESC
                ADD CONSTRAINT RELEASE.UN2160A
                UNIQUE( ID_MASK ) ;
        ALTER TABLE RELEASE.ACTION_DESC
                ADD CONSTRAINT RELEASE.UN2160B
                UNIQUE( NAME ) ;
ALTER TABLE RELEASE.ACTION_SET
                ADD CONSTRAINT RELEASE.UN2120A
                UNIQUE( "ID" ) ;
        ALTER TABLE RELEASE.ACTION_SET
                ADD CONSTRAINT RELEASE.UN2120B
                UNIQUE( NAME ) ;
0

2 Answers 2

3
cat inputfile | tr '\n' '@' | sed -e 's/;/;\n/g' | grep UNIQUE | tr '@' '\n'
2
  • Useless use of Cat anyway
    – netmonk
    Commented Sep 30, 2015 at 8:17
  • Instead additional grep just add to sed : -e '/UNIQUE/!d'
    – Costas
    Commented Sep 30, 2015 at 10:14
1

You can do it by sed only

sed ':1;/ALTER/N;/;/!b1;/UNIQUE/!d' inputfile > outputfile

or same with pattern space use

sed 'H;/ALTER/h;/;/x;/UNIQUE/!d' inputfile > outputfile

Or you can use awk by same style:

awk 'b{b=b "\n" $0}/ALTER/{b=$0}/;/{if(b~/UNIQUE/)print b;b=""}' inputfile

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .