1

I have a space separated table (as in this example):

A 101
B 92 102
C 83 93 103
D 74 84 94 104
  ︙

I would like to obtain this:

  • sample A with the associated value and all the second column (starting from the first value of sample B) transposed in a row
    (in other words, the entire first row, followed by the second field from every subsequent row),
  • sample B with the associated values and all the second column (starting from the first value of sample C) transposed in a row
    (in other words, the entire second row, followed by the second field from every subsequent row),
  • etc.

This is the first five columns of the first four rows of my output:

A 101 92 83 74 …
B 92 102 83 74 …
C 83 93 103 74 …
D 74 84 94 104 …
0

1 Answer 1

4
awk '
{
    a[NR]=$0
    b[NR]=$2
}
END{
    for(i=1;i<=NR;i++){
        k=i+1
        printf("%s ",a[i])
        for(j=k;j<=NR;j++)
            printf("%s ",b[j])
        print ""
    }
}' table.file

At first script builds two arrays (a and b) with NR (row number) as index. Than add to each element of array a all elements of array b but without first k ones. For case of memory limitation the same can be done by double pass of input file:

awk '
NR==FNR{
    b[NR]=$2
    rows=NR
    next
}
{
    printf("%s ",$0)
    for(j=FNR+1;j<=rows;j++)
        printf("%s ",b[j])
    print ""
    }
}' table.file table.file
4
  • It works but i don't have blank line in my input file how can i fix the script? Feb 18, 2015 at 14:13
  • @IlarioFerrocino Let me see example
    – Costas
    Feb 18, 2015 at 14:28
  • my input file dose not have blank line as in the example Feb 18, 2015 at 14:35
  • @IlarioFerrocino I didn't see any empty line in output
    – Costas
    Feb 18, 2015 at 14:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .