Help with merge Shell Script

I have a file test.log
The content of the file is :

a:R_yz:1
a:R_cd:2
a:F_bc:0
a:F_xx:3
b:R_dg:5
b:R_gf:1
b:F_fd:4

I want the output is :

:a R_yz 1 3 3  
     :   R_cd 2
     :   F_bc 0
     :   F_xx 3

:b R_dg 5 6 4
     :    R_gf 1
     :    F_fd 4                                                          

NB: here 3 and 3 is R_yz + R_cd and F_bc + F_xx
6 and 4 is R_dg + R_gf and F_fd

Please help
Thanks in advance

awk -F: 'END {
  printf ":%s %s %s", p1, p2, v[1] 
  for (i = 1; i <= c; i += 2) 
    printf " %s", v + v[i + 1]
  print r    
  }
NR > 1 && p1 != $1 {
  printf ":%s %s %s", p1, p2, v[1] 
  for (i = 1; i <= c; i += 2)
    printf " %s", v + v[i + 1]
  print r; r = c = x; split(x, v)  
  }
{
  v[++c] = $3; p1 = $1; 
  c == 1 ? p2 = $2 : r = (r ? r : x) \
    RS "\t" FS OFS $2 OFS $3
  }' infile

Lol Radulov ... did you have fun ? :smiley: :smiley:

@Scruti,
can you do shorter ? :wink:

:smiley:

The repeating code should be encapsulated in a function :slight_smile:

Here's one using Perl -

$
$
$ cat f46
a:R_yz:1
a:R_cd:2
a:F_bc:0
a:F_xx:3
b:R_dg:5
b:R_gf:1
b:F_fd:4
$
$
$
$ perl -lne '
  /(.*?):(.*?)_.*:(\d+)$/ and ($a,$b,$c) = ($1,$2,$3);
  if ($.==1) {$sum=$c; push @x,$_;
  } elsif ($a eq $preva) {
    push @x,$_;
    if ($b eq $prevb) {$sum+=$c}
    else {push @y,$sum; $sum=$c}
  } else {
    push @y,$sum;
    for ($i=0; $i<=$#x; $i++) {
      if ($i==0) {
        $x[$i] =~ s/:/ /g;
        print ":$x[$i]  @y";
      } else {
        $x[$i] =~ s/^.*?:/ /; $x[$i] =~ s/:/ /;
        print ": $x[$i]"
      }
    }
    @y = (); $sum=$c; @x=(); push @x,$_;
  }
  $preva = $a;
  $prevb = $b;
  END {push @y,$sum;
       for ($i=0; $i<=$#x; $i++) {
         if ($i==0) {
           $x[$i] =~ s/:/ /g;
           print ":$x[$i]  @y";
         } else {
           $x[$i] =~ s/^.*?:/ /; $x[$i] =~ s/:/ /;
           print ": $x[$i]"
         }
       }
  }
' f46
:a R_yz 1  3 3
:  R_cd 2
:  F_bc 0
:  F_xx 3
:b R_dg 5  6 4
:  R_gf 1
:  F_fd 4
$
$

tyler_durden

OK, I'll have a go :):

awk -F: '{$1=$1;f=":%s\n%s\n";if($1!=p){if(p)printf f,s OFS (n""?n:x),r RS; s=$0;r=x;p=$1}
          else r=r (r?RS:x)"\t: "$2" "$3;n+=$3}!(t=!t){s=s OFS n;n=x}
          END{printf f,s OFS (n""?n:x),r}' infile
2 Likes

hey Scrutinizer this may be asking extra work from you but ,
i usually read this forum to learn things, the above command will do the job but if we see its like greek and latin
so it will be nice if u had 2 line description also in ur solution what u doing

Thanks a lot,
it's work fine