Shell – How to Subtract First Value from Last One Within a Column

awkperlsedshell

I have a data file looks like :

1 1 1 1 1 1 1 1 2 2 2 2 3 3 3 3 3 3 
2 4 5 8 9 10 13 17 19 29 30 32 33 50 700 800 900 950 

first I want to insert space among each 3 identical values keeping each three identical numbers together in one colum by looking at the first row :

1 1 1  1 1 1  1 1  2 2 2  2  3 3 3  3 3 3 
2 4 5  8 9 10  13 17  19 29 30  32  33 50 700  800 900 950

and then I want to subtract the first value from the last one within each new column at second row ( but if there was only one value at a specific column(here the forth column at second row), then the last value from the previous column should be subtracted from that value(32-30)) while keeping one unique number out of each column from the first row. so the final data should be like this:

1 1 1 2 2 3 3
3 2 4 11 2 667 150 

any suggestion please? meanwhile I should mention my real data is indeed huge and I want to group each 5 unique values at first row. I may want to change the size of group . So I need the script to be flexible ..

Best Answer

Perl to the rescue!

#!/usr/bin/perl
use warnings;
use strict;

my $group_size = 3;

my @first = split ' ', <>;

my @groups;
my $start_index = 0;
while ($start_index < @first) {
    my $step = 1;
    while ( $step < $group_size
            && $start_index + $step < @first
            && $first[$start_index] == $first[ $start_index + $step ]
          ) {
        ++$step;
    }
    push @groups, $step;
    print $first[$start_index], ' ';
    $start_index += $step;
}
print "\n";

my @numbers = split ' ', <>;

my $last;
for my $size (@groups) {
    my @group = splice @numbers, 0, $size;
    my $value = $group[-1] - $group[0];
    $value = $group[0] - $last if 1 == $size;
    $last = $group[-1];
    print $value, ' ';
}
print "\n";

You haven't specified what should happen if the very first group has just one member.

Related Question