user3238106
user3238106

Reputation: 11

Concatenating previous line with current line based on condition

I need help scripting the following. If the current Line starts with #STOP# and the previous line also starts with "#STOP#" then simply print the line. If current Line starts with "#STOP#" and previous line also starts with "MSG#" concatenate previous line to current line.

Input file:

#STOP# |package1| function1
#STOP# |package2|   function2
#MSG#  |package3| SQL1
#STOP# |package4|  MapperBean
#MSG#  |package3|  SQL2
#STOP# |package4|  MapperBean
#STOP# |package4|   MapperBean
#STOP# |package5|  ActionItem

Desired output:

#STOP# |package1| function1
#STOP# |package2|   function2
#STOP# |package4|  MapperBean  #MSG#  |package3| SQL1
#STOP# |package4|  MapperBean  #MSG#  |package3|  SQL2
#STOP# |package4|   MapperBean
#STOP# |package5|  ActionItem

Upvotes: 1

Views: 204

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85883

One way with awk:

$ awk '$1=="#MSG#"{msg=OFS $0;next}{print $0(msg?msg:"");msg=""}' file
#STOP# |package1| function1 
#STOP# |package2|   function2 
#STOP# |package4|  MapperBean #MSG#  |package3| SQL1
#STOP# |package4|  MapperBean #MSG#  |package3|  SQL2
#STOP# |package4|   MapperBean 
#STOP# |package5|  ActionItem 

Upvotes: 4

Related Questions