user3437245
user3437245

Reputation: 347

Print between two matches with awk

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

Answers (4)

Ed Morton
Ed Morton

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

Jose Ricardo Bustos M.
Jose Ricardo Bustos M.

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

123
123

Reputation: 11216

Using sed

sed '/output/{N;s/\n/:/;:1;N;/ENDD/!{s/\n/,/;b1}}' file

Upvotes: 0

slobobaby
slobobaby

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

Related Questions