Reputation: 347
I want to rearrange the input with the following line but I keep getting ENDD on the wrong line.
awk '/output/ {printf $0":";flag=1;next} /ENDD/{flag=0;} flag {printf $0 "," ;}{if (flag==0)print}' file
Input:
exam1
exam4 1
output
list2
frame 3
list 5
ENDD
col 1
cal 2
del 3
Output:
exam1
exam4 1
output:list2,frame 3,list 5,ENDD
col 1
cal 2
del 3
Desired Output:
exam1
exam4 1
output:list2,frame 3,list 5
ENDD
col 1
cal 2
del 3
Upvotes: 0
Views: 160
Reputation: 203189
$ cat tst.awk
/ENDD/ { print rec; inRec=0 }
inRec { rec = rec sep $0; sep="," }
/output/ { rec=$0 ; sep=":"; inRec=1 }
!inRec
$ awk -f tst.awk file
exam1
exam4 1
output:list2,frame 3,list 5
ENDD
col 1
cal 2
del 3
Upvotes: 2
Reputation: 8164
you can try
awk ' /output/ { printf "%s:",$0; flag=1; next }
/ENDD/{ print ""; flag=0; }
flag>1 { printf ","; }
flag { printf "%s",$0; flag++ }
!flag' file
you get
exam1 exam4 1 output:list2,frame 3,list 5 ENDD col 1 cal 2 del 3
edit: another solution
awk -v ini=output -v end=ENDD '
$0 ~ ini, $0 ~ end{
printf ($0~ini? "%s:" : ($0~end? "\n%s\n" : (prev ~ ini? "%s" : ",%s"))), $0;
prev=$0;
next;
} 1' file
Upvotes: 3
Reputation: 706
A simpler solution (than my original):
awk '/output/ {printf $0":";flag=1;idx=0;next} /ENDD/{printf last "\n";flag=0} flag {if (last) printf last ","; last=$0}{if (flag==0)print}' file
Upvotes: 0