Search code examples
stringunixsed

Delete a whole line on keeping the last specific character in unix


I want to delete all lines beginning with a key word CONSTRAINT in a file. But if the end of the line is "))" I want to keep the ") at the end.

For exemple, with input :

CONSTRAINT FK_TESTA  ( CD_AAA ))
CONSTRAINT FK_TESTB ( CD_BBB ),
CONSTRAINT FK_TESTD  ( CD_DDD ))
CONSTRAINT FK_TESTC ( CD_CCC ),

I want output:

)

)

I have tried to find the answers without result.


Solution

  • Since I don't know if you have version that supports more than POSIX BREs, this will use POSIX BREs.

    Two expressions:

    sed -e 's/^CONSTRAINT.*))$/)/' -e 's/^CONSTRAINT.*//'
    
    1. Match on lines starting with CONSTRAINT and ends with )). Replace the content in those lines with a single ).
    2. If what's left on the line starts with CONSTRAINT, remove all of it.