DBPlayer
DBPlayer

Reputation: 55

replacing a character found after a matching pattern using awk / sed

I have below type of contents in a file. I want to replace closing bracket symbol ) only if it appears after pattern REFERENCES

Please note that symbol ) does not have to be at end of the line

cat file1    
ALTER TABLE mytable1
       ADD  ( CONSTRAINT myconst1 FOREIGN KEY (fkeyid)
                             REFERENCES mytable2 ) ;
ALTER TABLE mytable5
       ADD  ( CONSTRAINT myconst1 FOREIGN KEY (fkeyid)
                             REFERENCES mytable6 )
 ;

Desired output

ALTER TABLE mytable1
       ADD  ( CONSTRAINT myconst1 FOREIGN KEY (fkeyid)
                             REFERENCES mytable2  ;
ALTER TABLE mytable5
       ADD  ( CONSTRAINT myconst1 FOREIGN KEY (fkeyid)
                             REFERENCES mytable6 
 ;

I tried few things but no luck

Upvotes: 0

Views: 209

Answers (1)

SLePort
SLePort

Reputation: 15461

With sed:

sed 's/\(REFERENCE[^)]*\))/\1/' file

Strings containing REFERENCE followed by non ) characters up to and excluding next ) character are captured and output using backreference.

Add the -i flag to edit the file in place:

sed -i 's/\(REFERENCE[^)]*\))/\1/' file

Edit:

To remove only when there is no opening bracket:

sed 's/\(REFERENCE[^(]*[^()]*\))/\1/' file

Upvotes: 1

Related Questions