Merging rows after matching a pattern

Hi All,

I have the below file where I want the lines to merged based on a pattern.

 
AFTER
CMMILAOJ
CMMILAAJ
AFTER
CMDROPEJ
CMMIMVIJ
CMMIRNTJ
CMMIRNRJ
CMMIRNWJ
CMMIRNAJ
CMMIRNDJ
AFTER
CMMIRNTJ
CMMIRNRJ
CMMIRNWJ
CMMIRNAJ
CMMIRNDJ
CMDMAETJ
 

I want to join lines starting from each "AFTER" word until the next "AFTER" word comes in below format. output should look like below, note the braces and commas.

 
AFTER (CMMILAOJ, CMMILAAJ)
AFTER (CMDROPEJ, CMMIMVIJ, CMMIRNTJ, CMMIRNRJ, CMMIRNWJ, CMMIRNAJ, CMMIRNDJ)
AFTER (CMMIRNTJ, CMMIRNRJ, CMMIRNWJ, CMMIRNAJ, CMMIRNDJ, CMDMAETJ)
 

An awk solution:

awk '
        !/AFTER/ {
                s = s ? s "," $0 : "(" $0
        }
        /AFTER/ && s {
                print "AFTER", s ")"
                s = ""
        }
        END {
                print "AFTER", s ")"
        }
' file

Use nawk or /usr/xpg4/bin/awk on Solaris.

1 Like

I tried that but gave me a syntax error

 
 
awk '
        !/AFTER/ {
                s = s ? s "," $0 : "(" $0
        }
        /AFTER/ && s {
                print "AFTER", s ")"
                s = ""
        }
        END {
                print "AFTER", s ")"
        }
' test.out

awk: syntax error near line 3
awk: illegal statement near line 3
awk: syntax error near line 5
awk: bailing out near line 5

Please use code tags, not icode tags for posting code fragments or data samples.

I told you before to use nawk or /usr/xpg4/bin/awk instead of awk on Solaris.

1 Like

Thanks a lot