try this,
perl -0777 -pe 's/,([^\n,]*\n[^\n]*PRIMARY)/)$1/g' This will replace the last , with ) in lines before any line including PRIMARY.
Explanation
perl -0777slurp whole file (read as one line)s/search_pattern/replacement/gSubstitute search pattern with replacement globally