awk to combine all matching dates and remove non-matching

Using the awk below I am able to combine all the matching dates in $1 , but I can not seem to remove the non-matching from the file. Thank you :).

file

20161109104500.0+0000,x,5631
20161109104500.0+0000,y,2
20161109104500.0+0000,z,2
20161109104500.0+0000,a,4117
20161109104500.0+0000,b,6182
20161109104500.0+0000,c,1556
618
225
41
4
20161109104500.0+0000,k,2689
20161109104500.0+0000,l,6182
20161109104500.0+0000,d,3241
20161109104500.0+0000,e,2418
20161109104500.0+0000,f,26
20161109104500.0+0000,g,285166.843750
20161109104500.0+0000,h,67216

awk with current output

awk -F',' '{if(a!=$1) {a=$1; printf "\n%s%s",$0,FS} else {a=$1;$1="";printf $0 }} END {printf "\n" }' file

20161109104500.0+0000,x,5631, y 2 z 2 a 4117 b 6182 c 1556
618,
225,
41,
4,
20161109104500.0+0000,k,2689, l 6182 d 3241 e 2418 f 26 g 285166.843750 h 67216

desired output

20161109104500.0+0000,x,5631, y 2 z 2 a 4117 b 6182 c 1556
20161109104500.0+0000,k,2689, l 6182 d 3241 e 2418 f 26 g 285166.843750 h 67216

Hello cmccabe,

If your Input_file is exactly the same as sample shown into your post then following may help you in same.

awk -F, '{if(A!=$1 && A && VAL ~ /,/){print VAL;VAL=""};VAL=A==$1?VAL OFS $2 OFS $3:$0;A=$1} END{print VAL}'   Input_file

Output will be as follows.

20161109104500.0+0000,x,5631 y 2 z 2 a 4117 b 6182 c 1556
20161109104500.0+0000,k,2689 l 6182 d 3241 e 2418 f 26 g 285166.843750 h 67216

NOTE: Above code considers that the 1st fields we have to match are on the basis of there next line not the whole Input_file. Input_file's non-matching lines will not have comma(,) in them.

If you have mor requirements in this, request you to be more clear into your post so that could try to help you more on same. I hope this helps.

Thanks,
R. Singh

1 Like

Shouldn't the output be:

20161109104500.0+0000,x,5631,y,2,z,2,a,4117,b,6182,c,1556,k,2689,l,6182,d,3241,e,2418,f,26,g,285166.843750,h,67216
awk 'NF==1{next} p!=$1{if(s) print s; p=$1; s=$0; next} {$1=x; s=s $0} END{if(s) print s}' FS=, OFS=, file
1 Like

Thank you both :slight_smile: