使用awk在两场比赛之间打印

时间:2015-09-16 09:54:43

标签: awk

我想用以下行重新排列输入,但我一直在错误的行上得到ENDD。

awk '/output/ {printf $0":";flag=1;next} /ENDD/{flag=0;} flag {printf  $0 "," ;}{if (flag==0)print}' file

输入:

exam1
exam4 1
output
list2
frame 3
list 5
ENDD
col 1
cal 2
del 3

输出:

exam1
exam4 1
output:list2,frame 3,list 5,ENDD
col 1
cal 2
del 3

期望的输出:

exam1
exam4 1
output:list2,frame 3,list 5
ENDD
col 1
cal 2
del 3

4 个答案:

答案 0 :(得分:3)

你可以尝试

awk ' /output/ { printf "%s:",$0; flag=1; next } 
      /ENDD/{ print ""; flag=0; } 
      flag>1 { printf ","; }
      flag { printf "%s",$0; flag++ }
      !flag' file

你得到了

exam1
exam4 1
output:list2,frame 3,list 5
ENDD
col 1
cal 2
del 3

编辑:其他解决方案

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

答案 1 :(得分:2)

$ 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

答案 2 :(得分:0)

一个更简单的解决方案(比我原来的):

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

答案 3 :(得分:0)

使用sed

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