Search code examples
bashshellawktextsed

Join every two lines after the expression in bash script


I have the following text file that contains:

Environment: MS001
GATEWAY TEST: CV_ST
EXECUTION-RESULT: 0
GATEWAY TEST: CV_T2
EXECUTION-RESULT: 0
GATEWAY TEST: CVI_T
EXECUTION-RESULT: 0
Environment: MT01
GATEWAY TEST: S_C
EXECUTION-RESULT: 0

I would like to obtain this result

Environment: MS001,GATEWAY TEST: CV_ST,EXECUTION-RESULT: 0
Environment: MS001,GATEWAY TEST: CV_T2,EXECUTION-RESULT: 0
Environment: MS001,GATEWAY TEST: CVI_T,EXECUTION-RESULT: 0
Environment: MT01,GATEWAY TEST: S_C,EXECUTION-RESULT: 0 

Basically group each gw by environment, I'm trying this but I can't get it

awk -F: '/^Environment/{ITM=$0} !/^Environment/{print ITM"=>"$0}'


Solution

  • If the two lines after "Environment" always contain the same terms (i.e. GATEWAY TEST and EXECUTION-RESULT) you could use:

    awk '/Environment/ {e = $0} /GATEWAY TEST/ {gt = $0} /EXECUTION-RESULT/ {print e "," gt "," $0}' file
    Environment: MS001,GATEWAY TEST: CV_ST,EXECUTION-RESULT: 0
    Environment: MS001,GATEWAY TEST: CV_T2,EXECUTION-RESULT: 0
    Environment: MS001,GATEWAY TEST: CVI_T,EXECUTION-RESULT: 0
    Environment: MT01,GATEWAY TEST: S_C,EXECUTION-RESULT: 0